我有以下结构:
{
"_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
}
]
}
我想
$addFields
is_liked
如果likedBy
数组包含user_id
和$project
:likedBy: 0
隐藏该数组 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基本上,最终结果是将
likedBy
数组替换为is_liked: true/false
,因此我不必将数组携带在FE中只是为了检查用户是否喜欢 最佳答案
您可以使用$mergeObjects将现有的tweet与is_liked
字段组合在一起,然后使用$project从最终结果中排除likedBy
数组,请尝试:
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
}
}
])