简体   繁体   中英

How to filter data based on input array in mongodb?

I am receiving an Input from front-end like this

{
"options":[
      {
          "optionId":"5ebbe0f56b197f36fc472168"
      },
      {
           "optionId":"5ebbe1aa6b197f36fc47216e"
      }
]

}

I want to filter data in a way such that when I filter data I should receive an array of object which contains both these two id's

I have structure from where I need to find this

"answersArray" : [
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89ba"),
        "questionId" : ObjectId("5ebbe00e6b197f36fc472161"),
        "answerId" : ObjectId("5ebbe00e6b197f36fc472162")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b9"),
        "questionId" : ObjectId("5ebbe0f56b197f36fc472168"),
        "answerId" : ObjectId("5ebbe0f56b197f36fc472169")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b8"),
        "questionId" : ObjectId("5ebbe1aa6b197f36fc47216e"),
        "answerId" : ObjectId("5ebbe1aa6b197f36fc47216f")
    }
],

"answersArray" : [
    {
        "_id" : ObjectId("5ede620ea6979e5128bb89b5"),
        "questionId" : ObjectId("5ebbd4e76b197f36fc47211e"),
        "answerId" : ObjectId("5ebbd4e76b197f36fc47211f")
    },
    {
        "_id" : ObjectId("5ede620ea6979e5128bb89b4"),
        "questionId" : ObjectId("5ebbd5516b197f36fc472120"),
        "answerId" : ObjectId("5ebbd5516b197f36fc472121")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b8"),
        "questionId" : ObjectId("5ebbe1aa6b197f36fc47216e"),
        "answerId" : ObjectId("5ebbe1aa6b197f36fc47216f")
    },

]

I am expecting this answer

 "answersArray" : [
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89ba"),
        "questionId" : ObjectId("5ebbe00e6b197f36fc472161"),
        "answerId" : ObjectId("5ebbe00e6b197f36fc472162")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b9"),
        "questionId" : ObjectId("5ebbe0f56b197f36fc472168"),
        "answerId" : ObjectId("5ebbe0f56b197f36fc472169")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b8"),
        "questionId" : ObjectId("5ebbe1aa6b197f36fc47216e"),
        "answerId" : ObjectId("5ebbe1aa6b197f36fc47216f")
    }
],

How can I filter this any suggestions?

You want to use $all .

db.collection.findOne(
    {
        "answersArray.questionId": {$all: options.map(id => ObjectId(id))}
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM