如何在猫鼬聚合期间有条件地投射字段

时间:2018-08-31 11:11:55

标签: mongodb mongoose aggregation-framework

我有一个类似的问题文件。

[
 {
   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:我稍作更新,观众中的对象具有多个键值对。即userIDviewedAtfilledAt

1 个答案:

答案 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"]
    }
  }
 }
])