赵彬杰
赵彬杰

Reputation: 43

$replaceRoot in mongodb aggregation

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.

Upvotes: 3

Views: 1826

Answers (2)

Ashh
Ashh

Reputation: 46481

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

Upvotes: 4

Hardik Shah
Hardik Shah

Reputation: 4210

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

Upvotes: 1

Related Questions