本文介绍了Mongodb:组合$ in和$ nin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的收藏集posts中,我有这样的文档

In my collection posts I've documents like this

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

}]

我需要进行一些查询,在这些查询中,我将根据它们的category_id(可以是多个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.

我已经尝试过查询(在shell中):

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")']}}
]})

如果count()我返回0.

I returns 0 if count().

但是,如果我更改category_id属性并删除$ in并仅包含一个一个 ID,它就会起作用,就像这样:

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.

如何以与上述相同的方式将$ in和$ nin与objectId结合在一起?

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

推荐答案

这将起作用,只需删除ObjectId周围的单引号

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")]}}
]})

您不应在ObjectId周围加上单引号,否则会使它们成为字符串

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

这篇关于Mongodb:组合$ in和$ nin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 08:43