2016-01-22 51 views
1

我对查询的集合与:为什么子文档查询的顺序会影响MongoDB中的结果?

> db.things.find({ "entity":{entityType:"Location", id: "26802"}}) 

返回0的结果,但如果我与entityTypeid模式查询:

> db.things.find({ "entity":{id: "26802", entityType:"Location"}}) 

3返回结果。

3结果也返回两种:

> db.things.find({ "entity.id": "26802", "entity.entityType":"Location"}) 
> db.things.find({ "entity.entityType":"Location", "entity.id": "26802"}) 

这是为什么?

上有entity

{ 
    "v" : 1, 
    "key" : { 
     "entity" : 1 
    }, 
    "name" : "entity_1", 
    "ns" : "db_name.things" 
} 
+0

刚刚发现它的文档,而不是一个错误。 https://docs.mongodb.org/manual/core/index-single/#indexes-on-subdocuments,但我仍然不明白为什么这将是有用/不令人惊讶的行为。 – lyjackal

回答

3

指数转寄此link

这个查询,entity字段必须嵌入文档完全匹配。

> db.things.find({ "entity":{entityType:"Location", id: "26802"}}) 

只有比赛

entity: { 
    entityType:"Location", 
    id: "26802" 
} 

,而不是这个对象

entity: { 
    id: "26802" 
    entityType:"Location", 
} 

然而,这两个查询下面可以匹配上述两个对象,因为此查询的文件相匹配,其中entity字段包含一个嵌入文档,其字段为id,值为"26802"以及值"Location"的字段entityType

> db.things.find({ "entity.id": "26802", "entity.entityType":"Location"}) 
> db.things.find({ "entity.entityType":"Location", "entity.id": "26802"}) 
相关问题