$replaceRoot in mongodb aggregation

前端 未结 2 1810
孤城傲影
孤城傲影 2021-01-21 17:15

I have a collection like this:

{
    \"_id\" : ObjectId(\"5bd1686ba64b9206349284db\"),
    \"type\" : \"Package\",
    \"codeInstances\" : [ 
        {
                  


        
相关标签:
2条回答
  • 2021-01-21 17:23

    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" }
    ]
    
    0 讨论(0)
  • 2021-01-21 17:25

    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" }}
    ])
    
    0 讨论(0)
提交回复
热议问题