问题描述
我具有以下结构:
{
"_id":"some_id",
"tweets":[
{
"id":"1077633161922785281",
"created_at":"Tue Dec 25 18:32:21 +0000 2018",
"favorite_count":1905,
"retweet_count":27,
"media":[
],
"text":"Chillin",
"avatar":"https://pbs.twimg.com/profile_images/1062579676508381184/gDukIs20_normal.jpg",
"name":"Chance Morris",
"display_name":null,
"user_id":"1087348778",
"likedBy":[
"some-random-dude"
],
"likes":1
}
]
}
如果likedBy
数组包含user_id
和$project
:likedBy: 0
隐藏数组,我想$addFields
is_liked
I would like to $addFields
is_liked
if likedBy
array contains user_id
and $project
:likedBy: 0
to hide the array
db().collection('gamers').aggregate([
{
$project: {
'tweets.likedBy': 0
}
},
{
$addFields: {
'tweets.is_liked': {
$map: {
input: "$tweets",
as: "tweet",
in: {
id: "$$tweet.id",
text: "$$tweet.text",
is_liked: { $in: [ "some-random-dude", { $ifNull: [ "$$tweet.likedBy", [] ] } ] }
}
}
}
}
} ])
问题在于,在每个项目中都重复了$map
数组:屏幕快照: https://prnt.sc/lzrwln
The issue is that the $map
array is repeated in every item: screenshot: https://prnt.sc/lzrwln
基本上,最终结果是将likedBy
数组替换为is_liked: true/false
,因此我不必为了检查用户是否喜欢而在FE中携带该数组
Basically the end result would be replacing the likedBy
array with is_liked: true/false
, so I will not have to carry the array in FE just to check if the user liked or not
推荐答案
您可以使用 $ mergeObjects 将现有的tweet与is_liked
字段合并,然后使用 $ project 从最终结果中排除likedBy
数组,请尝试:
You can use $mergeObjects to combine existing tweet with is_liked
field and then use $project to exclude likedBy
array from final result, try:
db.gamers.aggregate([
{
$project: {
tweets: {
$map: {
input: "$tweets",
as: "tweet",
in: {
$mergeObjects: [
"$$tweet",
{ is_liked: { $in: [ "some-random-dude", { $ifNull: [ "$$tweet.likedBy", [] ] } ] } }
]
}
}
}
}
},
{
$project: {
"tweets.likedBy": 0
}
}
])
这篇关于MongoDB $ addFields和$ in总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!