Timofey Biryukov
Timofey Biryukov

Reputation: 376

node.js, mongoose how to find in array of objects by multiple IDs

I am using Node.js with Mongoose module and ran in to a problem.

I have a Schema mockup which looks like this:

_id: '',
foo: '',
bar: '',
fb: [{
    id: ''
}]

How do I find all objects in collection for matching fb[0].id plus passing in an array of IDs?

I have tried this (find() method with following query):

{'fb[0].id': {$in: friendsIDList}}

And this:

{'fb': {$in: [{id: friendsIDList}]} }

And even this

{'fb': {$in: {$in: friendsIDList}}}

To be more clear, I have an users object which contains their FB data in fb param, but it is an array containing just one object with data. Now I receive a friend IDs list and want to query all of the user friends.

Upvotes: 1

Views: 5567

Answers (1)

José F. Romaniello
José F. Romaniello

Reputation: 14156

MongoDB has something called dot notation so you can query with 'foo.0.id': 'id' .

Tested as follows:

> db.users.insert({foo: 'foo', bar: 'bar', fb: [ { id: '456' } ]})
> db.users.find({'fb.0.id': '456'}).pretty()
{
    "_id" : ObjectId("52fb695e403fb143985459dc"),
    "foo" : "foo",
    "bar" : "bar",
    "fb" : [
        {
            "id" : "456"
        }
    ]
}

Upvotes: 3

Related Questions