mongodb返回子文档

时间:2018-07-17 03:10:15

标签: mongodb mongodb-query

我正在使用3.2.3版。我如何获得仅返回cfmstatus == 'down'子文档而不是整个文档的功能?

db.test1.insert({
  _id: "host1",
  "interfaces" : [
    {
      "inf": "ge-10/3/5",
      "cfmstatus": "up"
    },
    {
      "inf": "ge-7/1/2",
      "cfmstatus": "down"
    }
  ]
});

db.test1.find({
  $where: function () {
      for (var index in this.interfaces)
          if (this.interfaces[index].cfmstatus == 'down')
              return this;
  }
});

谢谢。

2 个答案:

答案 0 :(得分:0)

根据上述问题的描述,作为解决方案,请尝试执行以下mongodb查询

db.getCollection("test1").find({
    interfaces: {
        $elemMatch: {
            cfmstatus: 'down'
        }
    }
}, {
    'interfaces.$': 1
})

在上面的查询中,$ elemMatch运算符用于将值过滤到数组元素中,而位置运算符$将返回属于嵌入式文档的第一个匹配子文档。

答案 1 :(得分:0)

使用$elemMatch

db.test1.find( { interfaces: { $elemMatch: {  cfmstatus: down } } } )

https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch“ $ elemMatch文档”

相关问题