2017-06-06 80 views
0

试图找到一种方法来达到子子字段之间的动态子字段。不知道如何到达那里。寻找像$用于数组的东西。MongoDB通过嵌套动态子字段进行搜索

我的数据结构如下所示

{ 
    _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

这应该工作

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

}})

+0

谢谢!谢谢 !!谢谢 !!! 正是我在找的东西。 –

+0

现在我正在寻找适合在芒果糖 –

+0

这很高兴它帮助.. !!。你能够适应这个猫鼬? –

0

等效上述文件,因为所有的数据属于共同的实体,在查询数据有利于方便性可以被表示为一个嵌入的文档从使用$elemMatch运算符的嵌入式文档。它的表示应该如下所示。

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

根据描述在上面提到的问题,获取文件中色域的值是黑色的请尝试在MongoDB中壳执行下面的查询。

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