0

I have a collection setup with documents that look like :

     {
        "_id" : ObjectId("5c786d9486c1140b1452d777"),
        "code" : "TEST-123",
        "owner" : "John",
        "cars" : [ 
            {
                "carPlate" : "QPZ-756",
                "carColor" : "blue"
            }, 
            {
                "carPlate" : "REF-473",
                "carColor" : "red"
            }
        ],
     }

I'm looking for an mongo aggregate query that grabs each carPlate and outputs the following for every document in the collection

        {
           "carPlate" : "QPZ-756",
           "owner" : "John",
           "code" : "TEST-123",
        },
        {
           "carPlate" : "REF-473",
           "owner" : "John",
           "code" : "TEST-123",
        },

I had a look at the $map operator, would this be a good place to start?

1 Answer 1

1

I would use $unwind to flatten the array followed by $mergeObjects to combine keys along with $replaceRoot to promote the merge documents to the top.

Something like

db.colname.aggregate([
    {$unwind:"$cars"},
    {$replaceRoot:{newRoot:{$mergeObjects:[{owner:"$owner"}, "$cars"]}}}
])
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.