Mongo: If any array position matches single query

怎甘沉沦 提交于 2019-12-25 06:58:08

问题


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}})


来源:https://stackoverflow.com/questions/28644850/mongo-if-any-array-position-matches-single-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!