MongoDB通过嵌套动态子字段进行搜索

时间:2017-06-06 17:12:07

标签: mongodb mongodb-query

试图找到一种到达子子字段的方法,其中包含动态子字段。不知道如何到达那里。寻找像$用于数组的东西。

我的数据结构类似于

  {
    _id: ObjectId("59355deee13f1a1260f17421"),
    product: {    
      shirt: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17422"),
    product: {    
      top: {
        color: "red"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17423"),
    product: {    
      shoes: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17424"),
    product: {    
      belt: {
        color: "brown7"
      }
    }
  },

寻找相应的

db.things.find({product.$.color: "black"})

2 个答案:

答案 0 :(得分:2)

这应该有效

db.getCollection('things').find({$where: function() { 
for (var field in this.product) { 
    if (this.product[field].color == "black") return true;
}
return false;

}})

答案 1 :(得分:0)

上述文档可以表示为嵌入式文档,因为所有数据都属于公共实体,便于使用$elemMatch运算符从嵌入式文档中查询数据。它的表示应如下所示。

{
    "_id": ObjectId("59355deee13f1a1260f17421"),
    "product": [{
            "name": "shirt",
            "color": "black"
        },
        {
            "name": "top",
            "color": "red"
        },
        {
            "name": "shoes",
            "color": "black"
        },
        {
            "name": "belt",
            "color": "brown7"
        }
    ]
}

根据上述问题中提到的描述获取色域值为黑色的文档,请尝试在MongoDB shell中执行以下查询。

db.things.find({product:{$elemMatch:{color:'black'}}})
相关问题