Ashh
Ashh

Reputation: 46491

query to get all _id in array in mongdb?

I have following collection

{
    "_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"),
}

how to get all _id in an array having same venue

My output should be like this

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

Upvotes: 0

Views: 98

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

db.collection.aggregate(

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

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

  ]


);

Upvotes: 0

Rahul Raj
Rahul Raj

Reputation: 3459

Try this query:

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

And the output is:

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

Upvotes: 3

Related Questions