[英]MongoDB find all not in this array
I'm trying to find all users except for a few, like this: 我试图找到除少数用户以外的所有用户,如下所示:
// get special user IDs
var special = db.special.find({}, { _id: 1 }).toArray();
// get all users except for the special ones
var users = db.users.find({_id: {$nin: special}});
This doesn't work because the array that I'm passing to $nin
is not and array of ObjectId
but an array of { _id: ObjectId() }
这不起作用,因为我传递给$nin
数组不是ObjectId
的数组,而是{ _id: ObjectId() }
的数组
Variable special
looks like this after the first query: 第一次查询后,变量special
看起来像这样:
[ { _id: ObjectId(###) }, { _id: ObjectId(###) } ]
But $nin
in the second query needs this: 但是在第二个查询中$nin
需要这个:
[ ObjectId(###), ObjectId(###) ]
How can I get just the ObjectId()
in an array from the first query so that I can use them in the second query? 如何从第一个查询中获取数组中的ObjectId()
,以便我可以在第二个查询中使用它们?
Or, is there a better way of achieving what I'm trying to do? 或者,有没有更好的方法来实现我想要做的事情?
Use the cursor.map()
method returned by the find()
function to transform the list of { _id: ObjectId(###) }
documents to an array of ObjectId
's as in the following 使用cursor.map()
由返回方法find()
函数的列表变换{ _id: ObjectId(###) }
文件的阵列ObjectId
的如下面
var special = db.special.find({}, { _id: 1 }).map(function(doc){
return doc._id;
});
Another approach you can consider is using the $lookup
operator in the aggregation framework to do a "left outer join" on the special
collection and filtering the documents on the new "joined" array field. 您可以考虑的另一种方法是使用聚合框架中的$lookup
运算符在special
集合上执行“左外连接”,并在新的“已连接”数组字段上过滤文档。 The filter should match on documents whose array field is empty. 过滤器应匹配数组字段为空的文档。
The following example demonstrates this: 以下示例演示了这一点:
db.users.aggregate([
{
"$lookup": {
"from": "special",
"localField": "_id",
"foreignField": "_id",
"as": "specialUsers" // <-- this will produce an arry of "joined" docs
}
},
{ "$match": { "specialUsers.0": { "$exists": false } } } // <-- match on empty array
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.