2016-01-22 50 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"}) 
相關問題