Home > database >  Mongodb: Return all except some documents where element matches
Mongodb: Return all except some documents where element matches

Time:11-11

Let say this is my database:

[
    {
        _id: 0,
        array: ["foo", "bar", "baz"],
    },
    {
        _id: 0,
        array: ["foo", "bar"],
    },
    {
        _id: 0,
        array: ["foo"],
    }
]

Now I need is :

{
    _id: 0,
    array: ["foo", "bar", "baz"],
},
{
    _id: 0,
    array: ["foo", "bar"],
},

Where we exclude foo but on only single element.

I tried with,

{
   "array":{
      "$not":{
         "$eq":"foo"
      }
   }
}

CodePudding user response:

You should compare it with whole array of only 1 element. (i.e. ["foo"])

db.collection.find({
  array: {
    $ne: [
      "foo"
    ]
  }
})

Mongo Playground

  • Related