0

In my collection posts I've documents like this

[{
  _id : ObjectId("post-object-id"),
  title : 'Post #1',
  category_id : ObjectId("category-object-id")

}]

I need to make some queries where I those a range of posts based on their category_id (can be multiple ids) but exclude some of them.

I've tried with the query (in shell):

db.posts.find({$and: [
  {_id: { $nin : ['ObjectId("post-object-id")']}}, 
  {category_id : { $in : ['ObjectId("category-object-id")']}}
]})

I returns 0 if count().

However, if I change the category_id attribute and remove the $in and just include one ID it work, like this:

db.posts.find({$and: [
  {_id: { $nin : ['ObjectId("58a1af81613119002d42ef06")']}}, 
  {category_id : ObjectId("58761634bfb31efd5ce6e88d")}
]})

but this solution only enables me to find by one category.

How would I got about combining $in and $nin with objectId's in the same manner as above?

Emil Devantie Brockdorff
  • 4,724
  • 12
  • 59
  • 76

1 Answers1

3

This will work, just remove single quotes around ObjectId

db.posts.find({$and: [
  {_id: { $nin : [ObjectId("post-object-id")]}}, 
  {category_id : { $in : [ObjectId("category-object-id")]}}
]})

You should not put single quotes around ObjectId, it make them strings

Puneet Singh
  • 3,477
  • 1
  • 26
  • 39
  • Thanks a bunch. I could swear that I already tried that, without the quotes around ObjectId, with no luck but apparently I haven't done it correct. Now it's working :-) – Emil Devantie Brockdorff Feb 15 '17 at 06:50