简体   繁体   中英

MongoDB aggregation results in an Array

I made some MongoDB aggregation like this:

db.first_collection.aggregate(
[
  { $lookup: {
        from:"second_collection",
        localField:"fisrt_id",
        foreignField:"second_id",
        as:"result"
      }
  },
  { $redact: {
        $cond: {
           if: { "$eq": [ "$result", [] ] },
           then: "$$DESCEND",
           else: "$$PRUNE"
         }
       }
  },
]
)

The output is:

{ "_id" : ObjectId("5a32249969e74c004161acc8"), "name" : "n1", "createdAt" : ISODate("2017-12-14T07:13:28.048Z"), "updatedAt" : ISODate("2017-12-14T07:13:28.048Z"), "result" : [ ] }
{ "_id" : ObjectId("5a69a60382e7d3002e6c7c74"), "name" : "n2", "createdAt" : ISODate("2018-01-25T09:40:19.098Z"), "updatedAt" : ISODate("2018-01-25T09:43:46.508Z"), "result" : [ ] }

Instead of Objects , I need an array containing only IDs. like:

["5a32249969e74c004161acc8", "5a69a60382e7d3002e6c7c74"]

Please let me know how?

try this

db.getCollection('TEST').aggregate([
    {$group:{
           "_id":"",
            "id":{
                $push : "$_id"
            }
    }},
    {$project:{"id":1,"_id":0}}
])

Output

{
    "id" : [ 
        ObjectId("5a5c99d2a8cb4105acaa6b96"), 
        ObjectId("5a5c99dfa8cb4105acaa6b99")
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM