Mongodb: Combine $in and $nin

情到浓时终转凉″ 提交于 2019-12-12 04:25:15

问题


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



来源:https://stackoverflow.com/questions/42225802/mongodb-combine-in-and-nin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!