首页 文章

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

提问于
浏览
0

我'm new to node js with mongodb programming. I' m使用 mongodb 模块,我想用用户公开信息执行"join"的帖子 . 我现在使用的代码如下:

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 ,查找也没有将对象绑定到结果数组 .

UPDATE 即使将$ 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

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

    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)})
    

相关问题