Home > Mobile >  Mongoose find record where array contains 2 elements that are provided
Mongoose find record where array contains 2 elements that are provided

Time:02-24

Hello everyone, I have a collection in which there is 1 boolean and an array that contains two strings. ex.

{
    "_id" : ObjectId("62148497fc3ac7c59252b53b"),
    "members" : [ 
        "61e4f988b92b443b29c87c38", 
        "61f0dd62e21a45de185854e9"
     ],
     "isGroup" : false,
     "createdAt" : ISODate("2022-02-22T06:37:11.406Z"),
     "updatedAt" : ISODate("2022-02-22T06:37:11.406Z"),
     "__v" : 0
}

now I want to find records where that members array contains those two strings and also isGroup is false. I'm passing two strings that are in members from frontend.

CodePudding user response:

Use $all

db.collection.find({
  members: {
    "$all": [
      "61e4f988b92b443b29c87c38",
      "61f0dd62e21a45de185854e9"
    ]
  },
  isGroup: false
})

mongoplayground

CodePudding user response:

If you want to search exact document which contains only these 2 values and the boolean, You can use the following code

db.collection.find({
    members:[
        "61e4f988b92b443b29c87c38",
        "61f0dd62e21a45de185854e9"
    ],
    isGroup: false
})

Instead, use the $all operator to locate an array that contains both the entries, regardless of order or other members in the array, Use the following code

db.collection.find({
    members:{$all:[
        "61e4f988b92b443b29c87c38",
        "61f0dd62e21a45de185854e9"
    ]},
    isGroup: false
})

Further readings MongoDB documentation

  • Related