How to do an $elemMatch query?

Hi !

I need to do this query with Parse, is it possible ?

db.User.find({
     "friends.bestFriends" : { $elemMatch : { "objectId" : "xkdUOWAoUI"}}
})

Is the $elemMatch implemented ? I see in the sources that it is used by another type of query, but i’m not sure how to use it for my usage.

And the data looks like :

{ 
friends:  {
    bestFriends : [
                          { "objectId" : "xkdUOWAoUI" , name : "Bob" },
                          { "objectId" : "ASfoiwePO" , name : "John" }
                        }
             }
}

Have a great day !

I think you can currently only use $elemMatch operation via aggregate. But, I believe the query below should work for you:

db.User.find({
     "friends.bestFriends.objectId" : "xkdUOWAoUI"
})
1 Like

hey @davimacedo

I would never have tought it could be that simple and you could query/traverse element arrays using the . notation. This is amaizing!!

So to search all the people who are friend with Bob but not John you can simply do :

const q = new Parse.Query(Parse.User)
q.equalTo('friends.bestFriends.objectId',  'xkdUOWAoUI')
q.notEqualTo('friends.bestFriends.objectId',  'ASfoiwePO')
await q.find()

There should probably have a note added to the docs, this is really useful to know!

Thanks!

Coo! I’m glad it’s working. Maybe we could add some examples to the Queries on Array section.

I added that to my to-do list. I’ll send a PR soon.

1 Like