Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Mongo value-in-array query: $not operator doesn't work, and ObjectIds cannot be selected

Tags:

mongodb

I am trying to select a document which does NOT contain a value in a document's array.

I'm having two problems, which I'll present separately:

(1) I cannot get the $not operator to work with a value-in-array query: 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 testing for the absence of orange:

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

Why does this not work?

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

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

The following does NOT retrieve this document:

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

Can someone suggest what I might be doing wrong?

like image 257
Aneil Mallavarapu Avatar asked Apr 17 '12 06:04

Aneil Mallavarapu


1 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, perhaps you're using the wrong number of ones.

like image 56
mu is too short Avatar answered Sep 28 '22 06:09

mu is too short