Mongodb-如何仅获取文档的一部分

时间:2018-12-15 23:55:14

标签: mongodb mongodb-query aggregation-framework

我的文档结构如下:

first: [{ 
    _id1: 'a',
    second: [{
        _id2: 'A',
        third: [{
            _id3: '1'
            name: 'name1',
            exampleField: 'xxx1'
        }, {
            _id3: '2'
            name: 'name2',
            exampleField: 'xxx2'
        }]
    }, {
        _id2: 'B',
        third: [{
            _id3: '3'
            name: 'name3',
            exampleField: 'xxx3'
        }, {
            _id3: '4'
            name: 'name4',
            exampleField: 'xxx4'
        }]
    }]
}, { 
    _id1: 'b',
    second: [{
        _id2: 'C',
        third: [{
            _id3: '5'
            name: 'name5',
            exampleField: 'xxx5'
        }, {
            _id3: '6'
            name: 'name6',
            exampleField: 'xxx6'
        }]
    }, {
        _id2: 'D',
        third: [{
            _id3: '7'
            name: 'name7',
            exampleField: 'xxx7'
        }, {
            _id3: '8'
            name: 'name8',
            exampleField: 'xxx8'
        }]
    }]
}]

如何仅获取名称等于“ name8”的“第三”数组的一部分?

我想得到这样的东西:

{ 
   _id1: 'a', 
   _id2: 'D', 
   _id3: '8', 
   name: 'name8', 
   exampleField: 'xxx8' 
}

我怀疑我必须使用$ filter或$ unwind,但是如何正确使用它?经过多次尝试,我再也没有想法了。

1 个答案:

答案 0 :(得分:0)

您可以使用$ unwind并在输出中提升所需的嵌套字段。 Working Sample

db.collection.aggregate([
  {
    $match: {
      "first.second.third.name": "name8"
    }
  },
  {
    $unwind: "$first"
  },
  {
    $unwind: "$first.second"
  },
  {
    $unwind: "$first.second.third"
  },
  {
    $match: {
      "first.second.third.name": "name8"
    }
  },
  {
    $project: {
      "_id": 0,
      "_id1": "$first._id1",
      "_id2": "$first.second._id2",
      "_id3": "$first.second.third._id3",
      "name": "$first.second.third.name",
      "exampleField": "$first.second.third.exampleField"
    }
  }
])