David Makovoz
David Makovoz

Reputation: 1918

Adding Index changes query result

I have a collection with the following schema:

db.posts.insert({sents:
    [
        {uni:['a','b','c'],bi:[['a','b'],['b','c']]},
        {uni:['x','y','z'],bi:[['x','y'],['y','z']]}
    ]})

the following query returns the record inserted above:

> db.posts.find({'sents.bi':{'$elemMatch':{'$in':['a']}}})
{ 
    "_id" : ObjectId("537595f254bae6dfabddf0c9"), 
     "sents" : [     
         { 
             "uni": [ "a", "b", "c" ],
             "bi": [[ "a", "b" ],  [ "b", "c" ] ] 
         },
         {
             "uni": [ "x", "y", "z" ],  
             "bi": [ [ "x",    "y" ],  [ "y", "z" ] ] 
         } 
     ] 
}

However, after I create an index on 'sents.bi':

>db.posts.ensureIndex({'sents.bi':1})

the above query stops working:

> db.posts.find({'sents.bi':{'$elemMatch':{'$in':['a']}}}).count()
0

I know I'm doing something wrong, I just don't know what it is that I'm doing wrong :)

Thank you,

Upvotes: 1

Views: 80

Answers (1)

yaoxing
yaoxing

Reputation: 4203

As the query you listed above doesn't give me anything with or without an index. I'm thinking do you possibly mean:

db.posts.find({'sents.bi':{'$elemMatch': {$elemMatch: {$in: ['a']}}}})

Note you got an array in an array. You'll have to do the $elemMatch twice.

Upvotes: 1

Related Questions