2014년 12월 16일 화요일

Trouble with multikey Indexes

I am running mongo db 2.4.9, (and I have also tested this script with 2.6.6)

I have created the script script.js,  and I do not understand the output that I am getting:

db.wtf.drop()
db.wtf.insert({a: [{b:'c', d: 'e'}]})
print(db.wtf.find({a: {b: 'c', d: 'e'}}).count() == 1)
print(db.wtf.find({a: {d: 'e', b: 'c'}}).count() == 1)

The output of the script is:

$ mongo testing script.js
MongoDB shell version: 2.4.9
connecting to: testing
true
false


Note that the order of the query {b: 'c', d: 'e'} vs {d: 'e', b: 'c'} seems to affect the output.  The first finds the document correctly while the second does not.



This is the intended behavior. From the MongoDB Manual page on query documents:

Equality matches on an embedded document require an exact match of the specified <value>, including the field order.

You can match the fields of the embedded doc inside the array without regard to order by using $elemMatch:

> db.ftfy.drop()
> db.ftfy.insert({ "a" : [{ "b" : "c", "d" : "e" }] })
> db.ftfy.count({ "a" : { "$elemMatch" : { "b" : "c", "d" : "e" } } }) == 1
true
> db.ftfy.count({ "a" : { "$elemMatch" : { "d" : "e", "b" : "c" } } }) == 1
true


댓글 없음:

댓글 쓰기