mongodb聚合与匹配,查找和项目

时间:2018-05-09 09:39:05

标签: node.js mongodb mongodb-query

我是使用mongodb编程的节点js的新手。我正在使用mongodb模块,我想用用户公开信息执行帖子“加入”。我现在使用的代码如下:

db.collection('post').aggregate({ 
  '$match': { category: 'video', status: 'online' },
  '$lookup': 
   { 
     from: 'user',
     localField: 'user',
     foreignField: '_id',
     as:'user'
  },
  '$project': 
     { text: 1,
       imgs: 1,
       video: 1,
       datetime: 1,
       user: 1,
       category: 1,
       marketplace: 1,
       tags: 1 } }
})
.toArray(function(err,posts){console.log(posts)})

但没有任何作用。即使类别不是music并且查找没有将对象绑定到结果数组,我也只会收到帖子。

更新 即使将$ match参数仅作为聚合查询

,聚合也不起作用

返回的集合是

[
  {
    "_id":"5aed6cbbd8362bcc0f2d95ab",
    "category":"music",
    "video":"",
    "imgs":[],
    "videoImage":false,
    "text":"post text",
    "tags":{["first","try"]}, 
    "datetime":1525509307968,
    "user":"FuRRTBEYBmCSDPJkN",
    "status":"online","marketplace":null}, 
  { 
    "_id":"5aedc26c6defa3d3a6de7126", "category":"music",
    "video":"https://www.youtube.com/embed/1yvLYJ2Fe_c", 
    "imgs" [],
    "videoImage":"https://i.ytimg.com/vi/1yvLYJ2Fe_c/hqdefault.jpg",
    "text":"second post text second post text second post text ",
    "tags":{["second","post"]},
    "datetime":1525531244425,
    "user":"FuRRTBEYBmCSDPJkN",
    "status":"online",
    "marketplace":null
   }
]

预期结果将是

[
  {
    "_id":"3aed6cbbd8362bcc0f2d95ab",
    "category":"video",
    "video":"",
    "imgs":[],
    "videoImage":false,
    "text":"post text",
    "tags":{["first","video"]}, 
    "datetime":1525509307968,
    "user": {_id: 'FuRRTBEYBmCSDPJkN', username: 'user1',img: '/path/to/the/image.png'},
    "status":"online","marketplace":null}, 
  { 
    "_id":"4aedc26c6defa3d3a6de7126", "category":"video",
    "video":"https://www.youtube.com/embed/1yvLYJ2Fe_c", 
    "imgs" [],
    "videoImage":"https://i.ytimg.com/vi/1yvLYJ2Fe_c/hqdefault.jpg",
    "text":"second video ",
    "tags":{["second","video"]},
    "datetime":1525531244425,
    "user":{_id: 'FuRRTBEYBmCSDPJkN', username: 'user1',img: '/path/to/the/image.png'},
    "status":"online",
    "marketplace":null
   }
]

1 个答案:

答案 0 :(得分:0)

就像Alex在评论中所说,我的问题的解决方案是将数组管道传递给聚合函数,如下所示。

db.collection('post').aggregate([
  '$match': { category: 'video', status: 'online' },
  '$lookup': 
   { 
     from: 'user',
     localField: 'user',
     foreignField: '_id',
     as:'user'
  },
  '$project': 
     { text: 1,
       imgs: 1,
       video: 1,
       datetime: 1,
       user: 1,
       category: 1,
       marketplace: 1,
       tags: 1 } }
])
.toArray(function(err,posts){console.log(posts)})