按子文档大小查找MongoDB文档

时间:2015-03-02 22:24:46

标签: mongodb mongodb-query

我有一个包含如下文档的集合:

{
    "_id" : ObjectId("..."),
    "some_key" : "some_value",
    ...,
    "another_key" : {
        "a key" : "a value",
        ...
    }
}

此系列中有几种不同类型的文档,最大的差异发生在“another_key”字段中。

我希望能够根据“another_key”中子文档的大小找到文档。如果它是一个数组,我可以使用这个查询:

{
    "another_key" : {
        $size : 0
    }
}

查找空白的所有文档。不幸的是,根据the documentation,这仅适用于数组。

有没有办法为子文档执行此操作?

2 个答案:

答案 0 :(得分:1)

使用Object.keys获取子文档密钥和$where运算符。

db.collection.find( { 
    'timestamp': "your value",
    '$where': function() { return Object.keys(this.another_key).length === 0; } 
})

答案 1 :(得分:1)

嵌套对象实际上不是子文档,我不会将它们称为子文档,因为它们不像文档那样行事,并且无法使用$他们的经营者。索引也没有真正起作用,但是我们可以索引另一个关键字'为了更好的搜索性能。

我建议将another_key转换为一个对象数组(子文档),如下所示:

db.items.insert({
    some_key : 'some_value',
    another_key : [
        {key: 'akey', value: 'avalue'},
        {key: 'bkey', value: 'bvalue'}
    ]
});

您现在可以按$ size找到,并根据需要输入密钥。

mongos> db.items.find({another_key: {$size: 0}})
 // 0 documents
mongos> db.items.find({another_key: {$size: 1}})
 // 0 documents
mongos> db.items.find({another_key: {$size: 2}})
 { "_id" : ObjectId("54f62a48e2fdcc95d4934424"), "some_key" : "some_value", "another_key" : [ { "key" : "akey", "value" : "avalue" }, { "key" : "bkey", "value" : "bvalue" } ] }
mongos> db.items.find({another_key: {$size: 3}})
 // 0 documents

mongos> db.collection.find({'another_key.key': 'akey'})
 { "_id" : ObjectId("54f62a48e2fdcc95d4934424"), "some_key" : "some_value", "another_key" : [ { "key" : "akey", "value" : "avalue" }, { "key" : "bkey", "value" : "bvalue" } ] }

很遗憾,您无法进行比较性$size查询:

mongos> db.items.find({another_key: {$size: {$gt:1} } } )
 error: {
     "$err" : "Can't canonicalize query: BadValue $size needs a number",
     "code" : 17287
 }