1

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?

2
  • can you add sample db data. Commented Mar 6, 2018 at 16:33
  • the db collections are huge, but I only need to join them on id. I came across "aggregation" and tried to do some "$project" after the "$redact", but it was not successful. Commented Mar 6, 2018 at 16:37

1 Answer 1

10

try this

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

Output

{
    "id" : [ 
        ObjectId("5a5c99d2a8cb4105acaa6b96"), 
        ObjectId("5a5c99dfa8cb4105acaa6b99")
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.