我正在为 MongoDB 开发一个聚合管道,并且我正在尝试检索用户不等于变量的项目。
由于某种原因,我无法让它工作。我尝试以不同的方式使用 $not
、$ne
和 $nin
,但无法使用。
看起来是这样的:
数据样本:
[{
"_id": { "$oid": "565674e2e4b030fba33d8fdc" },
"user": { "$oid": "565674832b85ce78732b7529" }
}, {
"_id": { "$oid": "565674e2e4b030fba33d8fdc" },
"user": { "$oid": "565674832b85ce78732b7529" }
}, {
"_id": { "$oid": "565674e2e4b030fba33d8fdc" },
"user": { "$oid": "56f9dfc5cc03ec883f7675d0" }
}]
管道示例(针对此问题进行了简化):
其中req.query.user.id = "565674832b85ce78732b7529"
collection.aggregate([
{
$match: {
user: {
$nin: [ req.query.user.id ],
}
}
}
]
这应该只返回最后一项。
您知道如何检索与用户不匹配的数据吗?
谢谢
编辑: 以下也不起作用:
collection.aggregate([
{
$match: {
'user.$oid': {
$nin: [ req.query.user.id ],
}
}
}
]);
我也试过 ObjectID()
并且 mongodb 提示:[MongoError: Argument must be a string]
var ObjectID = require('mongodb').ObjectID;
// Waterline syntax here
MyCollection.native(function (err, collection) {
collection.aggregate([
{
$match: {
'user': {
$nin: [ ObjectID(req.query.user.id) ],
}
}
}
], function (err, result) {
console.log(err, result);
});
});
但这一行在 shell 中有效:
db.collection.aggregate([{$match:{"user":{"$nin":[ObjectId("565674832b85ce78732b7529")]}}}])
最佳答案
基于答案 here ,你可以改变
var ObjectId = require('mongodb'). ObjectID;
到
var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID;
关于javascript - 聚合匹配管道不等于 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39910490/