查询在mongdb中获取数组中的所有_id?

时间:2018-04-11 11:38:49

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我有以下收藏

{
    "_id" : ObjectId("5acdb95d5ea63a27c1facf92"),
    "venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
    "author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
{
    "_id" : ObjectId("5acdb95d5ea63a27c1facf93"),
    "venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
    "author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
{
    "_id" : ObjectId("5acdb95d5ea63a27c1facf91"),
    "venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
    "author" : ObjectId("5ac8ba3582c2345af70d4658"),
}

如何在具有相同位置的数组中获取所有_id

我的输出应该是这样的

{array: ['5acdb95d5ea63a27c1facf91', '5acdb95d5ea63a27c1facf91', '5acdb95d5ea63a27c1facf93']}

2 个答案:

答案 0 :(得分:3)

尝试此查询:

db.colelction.aggregate([
  {$match:{"venue" : ObjectId("5acdb95d5ea63a27c1facf8c")}},
  {$group:{_id:null, array:{$push:"$_id"}}},
  {$project:{_id:0}}
])

输出是:

/* 1 */
{
   "array" : [ 
       ObjectId("5acdb95d5ea63a27c1facf92"), 
       ObjectId("5acdb95d5ea63a27c1facf93"), 
       ObjectId("5acdb95d5ea63a27c1facf91")
   ]
}

答案 1 :(得分:0)

db.collection.aggregate(

  // Pipeline
  [
    // Stage 1
    {
      $group: {
         _id:{venue:'$venue'},
         _ids:{$addToSet:'$_id'}
      }
    },

    // Stage 2
    {
      $project: {
      _ids:1,
      _id:0
      }
    }

  ]


);