使用不包含特定值的数组查找文档 [英] Find documents with array that doesn't contains a specific value
问题描述
我有以下模型:
var PersonSchema = new Schema({
name: String,
groups: [
{type: Schema.Types.ObjectId, ref: 'Group'}
],
});
我正在寻找一个查询来检索不属于某个组的所有人员(即人员的组数组不包含指定组的 id).
I am looking for a query that retrieves all the Persons that are not part of a certain Group (i.e the persons' group array doesn't contain the id of the specified group).
我正在考虑这样的事情,但我不确定它是否正确:
I was thinking about something like this, but I'm not sure it is correct:
Person.find({groups: {$nin: [group._id]})
推荐答案
您基本上尝试的内容没有错,但也许这里唯一的澄清是常见的误解,即您需要像 $nin
或 $in
查询数组时.
Nothing wrong with what you are basically attempting, but perhaps the only clarification here is the common misconception that you need operators like $nin
or $in
when querying an array.
此外你真的需要在这里做一个基本的不等式匹配$ne
:
Also you really need to do here is a basic inequality match with $ne
:
Person.find({ "groups": { "$ne": group._id } })
数组"运算符不是用于数组目标",而是用于以方便的形式提供要测试的条件列表".
The "array" operators are not for "array targets" but for providing a "list" of conditions to test in a convenient form.
Person.find({ "groups": { "$nin": [oneId, twoId,threeId] } })
因此只需对单个条件使用普通运算符,并保存 $in
和 $nin
以用于您想要针对单个值或一个值测试多个条件的地方列表.所以情况正好相反.
So just use normal operators for single conditions, and save $in
and $nin
for where you want to test more than one condition against either a single value or a list. So it's just the other way around.
如果您确实需要传递参数的列表",其中提供的列表中的无"与数组的内容匹配,那么您可以使用 $not
运算符和 $all
运算符:
If you do need to pass a "list" of arguments where "none" of those in the provided list match the contents of the array then you reverse the logic with the $not
operator and the $all
operator:
Person.find({ "groups": { "$not": { "$all": [oneId,twoId,threeId] } } })
所以这意味着数组中不存在提供的列表中的任何一个".
So that means that "none of the list" provided are present in the array.
这篇关于使用不包含特定值的数组查找文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!