查找所有对象,嵌套属性具有所需的值

时间:2015-02-19 11:40:24

标签: mongodb nosql

我收集了以下(样本)文件:

{
   "label": "Tree",
   "properties": {
       "height": {
           "type": "int",
           "label": "Height",
           "description": "In meters"
       },
       "coordinates": {
           "type": "coords",
           "label": "Coordinates"
       },
       "age": {
           "type": "int",
           "label": "Age"
       }
   }
}

属性属性中的键几乎与集合中的每个文档都不同。

我想查找至少包含一个属性的所有文档。

我正在寻找的是查询{"properties.*.type": "coords"}。但这不起作用,因为它只是我发明的mongo查询。

我能找到的每个帮助都关注我在这里无法使用的$elemMatch运算符,因为 properties 是一个对象,而不是一个数组。

2 个答案:

答案 0 :(得分:1)

嗨,据我所知,mongodb不提供这种搜索。因此,为了首先找到这个,我使用map-reduce分离出所有键,然后找到查询表单,所以下面的代码将帮助你

    var mapReduce = db.runCommand({
    "mapreduce": "collectionName",
    "map": function() {
    for (var key in this.properties) {
        emit(key, null);
    }
    },
    "reduce": function(key, stuff) {
    return null;
    },
    "out": "collectionName" + "_keys"
})

db[mapReduce.result].distinct("_id").forEach(function(data) {
    findkey = [];

    findkey.push("properties." + data + ".type");
    var query = {};
    query[findkey] = "coords";

    var myCursor = db.collectionName.find(query);

    while (myCursor.hasNext()) {
    print(tojson(myCursor.next()));
    }


})

答案 1 :(得分:1)

MongoDB不支持对密钥进行搜索 - 例如properties.*以匹配properties的所有子密钥等。您不应该拥有任意密钥或密钥。 ; t。在你的架构中知道,除非它们只是为了展示,一般来说,因为你将无法在MongoDB中轻松地与它们进行交互。

如果您确实想存储动态属性,最好的方法通常是如下数组:

{
    "properties" : [
        { 
            "key" : "height", 
            "value" : { 
                "type" : "Int", 
                "label" : "Height", 
                "description" : "In meters" 
             } 
         },
         ...
     ]
}

高效查询您的用例

  

查找至少具有给定类型属性的所有文档

来自{ "key" : 1 }的索引:

db.test.find({ "properties.key" : { "$in" : ["height", "coordinates", "age"] } })
相关问题