Mongo: If any array position matches single query

2019-09-07 03:33发布

问题:

Assuming this data structure:

{
    "title": "Foo bar",
    "username": "jackwreid"
},
{
    "title": "Bish bosh",
    "username": "lizziebump"
},
{
    "title": "Ham nam",
    "username": "lizziebump"
},
{
    "title": "Blub blub",
    "username": "jvarn"
}

And assuming

var userFollowing = ["lizziebump", "jackwreid"]

How would I do a db.posts.find() for posts where the username matches any of the contents of the userFollowing array?

I'm trying to build a query that returns posts by users in the current user's following list and I can only find docs on how to do this the other way around where the query returns posts if a single query string is in any array position.

回答1:

You can use the $in operator

db.collection.find({username: {$in: userFollowing}})