Issues with Mongo value-in-array query: $ not operator does not work, and ObjectIds cannot be selected

I am trying to select a document that does NOT contain a value in an array of documents.

I have two problems that I will cite separately:

(1) I cannot get the $ not operator to work with a value in an array: For example, if I have the following document in my collection:

{ _id: ObjectId("000000000000000000000000"), mylist: [ "red", "green", "blue" ] }

I can select this document using:

db.myCol.find({mylist:"red"})

However, I would like to select this document by checking the absence of orange:

db.myCol.find({$not:{mylist:"orange"}})

Why is this not working?

(2) I cannot get the value in the array request to work if the array values ​​are ObjectIds:

{ _id: Object("000000000000000000000000"), mylist: [ ObjectId("111111111111111111111111") ] }

Below this document is NOT retrieved:

myCol.find({mylist:ObjectId("111111111111111111111111")})

Can anyone suggest what I may be doing wrong?

+6
source share
3 answers

There is no $not that works like you want $ne for simple cases like yours:

 db.myCol.find({ mylist: { $ne: 'orange' } }) 

Your second should (and does) work fine for me, maybe you are using the wrong number of them.

+6
source

Alternatively, you can use $ not like this:

 { "mylist" : { $not : { $in : ["red"] } } } 
+3
source
 var queryarray = ['red'] db.myCol.find({ mylist: { $nin: queryarray } }) 
0
source

Source: https://habr.com/ru/post/913387/


All Articles