Mongodb: 查找至少有一个数组元素不匹配的所有文档?

Mongodb: Find all documents where at least one array element does not matches?

我在 Mongoose 中定义了一个组文档:

var GroupSchema = new Schema({
    name: String,
    sections: [{type: ObjectId}]
});

可见,组包含一组部分。我还有另一个名为 archived_sections

的 objectId 数组

我想找到至少有一个部分不在 archived_sections 数组中的所有组。怎么做?

我试图像这样使用 $nin 运算符:

Group.find({ sections: { $nin: archived_sections }).exec(function(err, groups){
  res.send(groups);
});

但这只给我那些 sections 字段包含一个数组的组,其中没有与数组中的元素匹配的元素 archived_sections。

我想找到至少一个部分不在 archived_sections 数组中的所有组。如何实现?请帮忙

您可以通过将 $nin 包装在 $elemMatch 运算符中来做到这一点,这样 $nin 将分别应用于 sections 的每个元素而不是元素作为一个组:

Group.find({ sections: { $elemMatch: { $nin: archived_sections } } })
    .exec(function(err, groups){
        res.send(groups);
    }
);

如果至少有一个元素满足 $elemMatch 查询,则文档匹配。