Home > Mobile >  multiple $ne in $and query in mongodb
multiple $ne in $and query in mongodb

Time:10-20

I'm trying to run a MongoDB Query in which I want to exclude specific documents.

my data is like this,

db.getCollection('tests').insertMany([
    { id: 1, make: "Honda" , model: "A1"}, <- this should be exclude
    { id: 1, make: "Honda" , model: "A2"},
    { id: 1, make: "Honda" , model: "A3"},
    { id: 1, make: "Hero" , model: "A4"},
    { id: 2, make: "Honda" , model: "A1"}, <- this should be exclude
])

I want to exclude the data which has { make: "Honda" } and { model: "A1" }.

I tried,

db.getCollection('tests').find({
  $and: [ 
    { id: 1}, 
    { make: {$ne: "Honda"} }, 
    { model: {$ne: "A1"} } 
  ]})

but it excludes all the documents with {make: "Honda"}

CodePudding user response:

db.collection.find({
  $or: [
    {
      make: {
        $ne: "Honda"
      }
    },
    {
      model: {
        $ne: "A1"
      }
    },
    {
      "id": {
        $ne: 1
      }
    }
  ]
})

This should do the job,

Playground

  • Related