MongoDB聚合导致数组

问题描述 投票:0回答:1

我做了一些像这样的MongoDB聚合:

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

输出是:

{ "_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" : [ ] }

我需要一个只包含ID的数组,而不是Objects。喜欢:

["5a32249969e74c004161acc8", "5a69a60382e7d3002e6c7c74"]

请告诉我怎么样?

mongodb
1个回答
2
投票

试试这个

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

产量

{
    "id" : [ 
        ObjectId("5a5c99d2a8cb4105acaa6b96"), 
        ObjectId("5a5c99dfa8cb4105acaa6b99")
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.