2

I have a Users Collection that looks like the following

{
    {
        _id: ObjectId(...),
        services: {facebook: {id: 1}}
    },
    {
        _id: ObjectId(...),
        services: {facebook: {id: 2}}
    },
    ...
}

Additionally, i have the following JavaScript array:

[
    {name: "Alice", id: 1},
    {name: "Bob", id: 3},
    ...
]

I want to find all users whose id is present in the array, but I could not find a way to "reach into" the JavaScript array.

2 Answers 2

1

You can use the array.map function to pull out the id values from the source array and then use those with an $in operator in a find like this:

var arr = [
    {name: "Alice", id: 1},
    {name: "Bob", id: 3},
    ...
];

db.users.find({'services.facebook.id': {$in: arr.map(function(e) {return e.id;})}});
Sign up to request clarification or add additional context in comments.

3 Comments

Out of curiosity I will ask smtg. Would this solution use indexes if there is any on id field? Or would this perform similar to $where query which can't use indexes?
@cubbuk Yes, it will use indexes. The arr.map call is made in the shell, so mongo just sees the resulting array of ids.
Thank you, I knew about array.map before but I was looking for a high-performance solution with less iterations. But obviously array.map is the only way...
0

First convert the javascript array into an array which contains only the raw ID's:

var yourArray = [ 1, 3 ];

Then try this query

db.yourCollection.find({ services.facebook.id : { $in : yourArray } });

Unfortunately there is no good way to let the database join the information from your local array (the name field) with the data returned from the database. So you will have to do this yourself. do a for-loop over the returned documents and find the real names by looking up the services.facebook.id field in your array.

By the way: Contrary to what you would do in an SQL database, artificial foreign keys (or foreign keys in general) should usually be avoided in MongoDB, because MongoDB isn't built to handle references as good as relational databases. It's often a good choice to embed data in a document instead of referencing it as a different document. The "all data must be normalized" dogma does not apply to a document database like MongoDB as much as it applies to relational databases.

1 Comment

Thank you for your answer. Of course I know that MongoDB data cannot be normalized and it isn't in my application, but since I have my users collection in my MongoDB and receive the array from another system (in my case Facebook), I need to do the "join" (which is a badly chosen term in connection with MongoDB but I can't come up with a better one).

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.