我有一个类似的问题文件。
[
{
type:"general",
viewers:[
{userId:"1", viewedAt:"10 Aug"},
{userId:"2", viewedAt:"12 Aug"}
]
},
{
type:"programming",
viewers:[
{userId:"3", viewedAt:"1 Aug"},
{userId:"2", viewedAt:"19 Aug"}
]
}
]
预期结果将添加名为viewed
的其他字段为:
如果给定userId
并假设userId:1
在查看者列表中,则添加viewed:true
其他viewed:false
如下:
[
{
"type":"general",
"viewed":"true"
},
{
"type":"general",
"viewed":"false"
}
]
我尝试了此代码,但显示错误:
Question.aggregate([
{
$project:{
type:1,
viewed:{
$cond:[
{$viewedBy:{"userId":1}},"true","false"
]
}
}
}
])
P.S:我稍作更新,观众中的对象具有多个键值对。即userID
,viewedAt
,filledAt
答案 0 :(得分:2)
在3.4中使用$in
聚合表达式。
Question.aggregate([
{
$project:{
type:1,
viewed:{
$cond:[ {$in:[{userId:"1"}, "$viewers"]},"true","false"]
}
}
}
])
OR
Question.aggregate([
{
$project:{
type:1,
viewed:{
$cond:[ {$in:["1", "$viewers.userId"]},"true","false"]
}
}
}
])