3

I have a collection like this:

{
    "_id" : ObjectId("5bd1686ba64b9206349284db"),
    "type" : "Package",
    "codeInstances" : [ 
        {
            "name" : "a",
            "description" : "a"          
        }, 
        {
            "name" : "b",
            "description" : "b1"
        }, 
        {
            "name" : "b",
            "description" : "b2"
        }
    ]
}
{
    "_id" : ObjectId("5bd16ab8a64b92068d485054"),
    "type" : "Package",
    "codeInstances" : [ 
        {
            "name" : "a",
            "description" : "a"          
        }, 
        {
            "name" : "b",
            "description" : "b3"
        }
    ]
}

The following structure is what I want:

{
      "name" : "b",
      "description" : "b1"
}, 
{
      "name" : "b",
      "description" : "b1"
}, 
{
      "name" : "b",
      "description" : "b3"
}

I tried this aggregate operations:

db.getCollection('t_system_code').aggregate([
  {"$unwind":"$codeInstances"},
  {$match:{"codeInstances.name":"b","type" : "Package"}},
  {"$project":{"codeInstances":1,"_id":0}}
]);

But thatundefineds not the structure I want:

{
    "codeInstances" : {
        "name" : "b",
        "description" : "b1"
    }
}
{
    "codeInstances" : {
        "name" : "b",
        "description" : "b2"
    }
}
{
    "codeInstances" : {
        "name" : "b",
        "description" : "b3"
    }
}

Help. Thank you.

1
  • make corrections:The following structure is what I want: { "name" : "b", "description" : "b1" }, { "name" : "b", "description" : "b2" }, { "name" : "b", "description" : "b3" } Commented Oct 30, 2018 at 7:35

2 Answers 2

4

You can try below aggregation using $replaceRoot

db.collection.aggregate([
  { "$match": { "codeInstances.name": "b", "type": "Package" }},
  { "$unwind": "$codeInstances" },
  { "$match": { "codeInstances.name": "b", "type": "Package" }},
  { "$replaceRoot": { "newRoot": "$codeInstances" }}
])
Sign up to request clarification or add additional context in comments.

Comments

1

You just need to project for name and description instead of whole codeInstances. Check below

db.collection.aggregate([
  { $unwind: "$codeInstances" },
  { $match: { "codeInstances.name": "b", "type": "Package" }},
  { $project: {
      "name": "$codeInstances.name",
      "description": "$codeInstances.description",
      "_id": 0
  }}
])

Output:

[
  { "description": "b1", "name": "b" },
  { "description": "b2", "name": "b" },
  { "description": "b3", "name": "b" }
]

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.