Mongodb: Combine $in and $nin

2019-09-06 23:39发布

问题:

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?

回答1:

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