2017-04-25 87 views
1

需要帮助构建这个mongo查询。 到目前为止,我可以在第一级别查询,但无法在接下来的嵌入级别这样做(“标签”> 2" )如何使用mongodb查询嵌入式文档

例如,文档结构如下:

> db.versions_20170420.findOne(); 
{ 
    "_id" : ObjectId("54bf146b77ac503bbf0f0130"), 
    "account" : "foo", 
    "labels" : { 
     "1" : { 
      "name" : "one", 
      "color" : "color1" 
     }, 
     "2" : { 
      "name" : "two", 
      "color" : "color2" 
     }, 
     "3" : { 
      "name" : "three", 
      "color" : "color3" 
     } 
    }, 
    "profile" : "bar", 
    "version" : NumberLong("201412192106") 

该查询我可以在第一级(account, profile)滤波器。

db.profile_versions_20170420.find({"account":"foo", "profile": "bar"}).pretty() 

然而,由于这种结构,我正在寻找的文件,其中"label">"2"它看起来并不像"2"。是多少,但是一个字符串。有没有办法构建mongo查询来做到这一点?我需要做一些转换吗?

回答

1

如果我正确理解你和你的数据结构,"label" > "2"意味着对象标签内容必须包括财产labels.3,而且很容易检查与下面的代码:

db.profile_versions_20170420.find(
    {"account": "foo", "profile": "bar", "labels.3": {$exists: true}} 
).pretty(); 

不过,这并不意味着你的对象包含至少3个属性,因为它不是$size函数,它计算数组中的元素的数量,并且我们不能使用$ size,因为labels是对象而不是数组。因此,在我们的案例中,我们只知道labels有属性3,即使它是标签包含的唯一属性。

可以提高查找条件:

db.profile_versions_20170420.find({ 
    "account": "foo", 
    "profile": "bar", 
    "labels.1": {$exists: true}, 
    "labels.2": {$exists: true}, 
    "labels.3": {$exists: true} 
}).pretty(); 

,并确保labes包含元素1, 2, 3,但在这种情况下,必须插入/更新过程中关心的应用程序级的对象结构/文件删除数据。

作为另一个选项,您可以更新数据库,并添加额外的场labelsConut之后,你将能够运行这样的查询:

db.profile_versions_20170420.find(
    {"account": "foo", "profile": "bar", "labelsConut": {$gt: 2}} 
).pretty(); 

顺便说一句,它的运行速度更快...