Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$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.

like image 242
赵彬杰 Avatar asked Feb 15 '26 01:02

赵彬杰


2 Answers

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" }}
])
like image 110
Ashh Avatar answered Feb 16 '26 17:02

Ashh


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" }
]
like image 22
Hardik Shah Avatar answered Feb 16 '26 15:02

Hardik Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!