查找数组不包含特定值的文档 [英] Find documents with array that doesn't contains a specific value

查看:88
本文介绍了查找数组不包含特定值的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

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

推荐答案

您的基本尝试没有错,但也许唯一的澄清是常见的误解,即您需要像 $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.

如果确实需要传递参数的列表",其中所提供列表中的参数没有"与数组的内容匹配,则可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆