1

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.

1 Answer 1

3

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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

what is the significance of 0 in fb.0.id ?
The id property of the first object in the array of the fb property. Like doing fb[0].id = 456 in most programming languages

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.