Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

javascript - Find documents with array that doesn't contains a specific value

I have the following model:

var PersonSchema = new Schema({
    name: String,
    groups: [
        {type: Schema.Types.ObjectId, ref: 'Group'}
    ],
});

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...