聚合匹配管道不等于 MongoDB
Aggregate match pipeline not equal to in MongoDB
我正在为 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 ],
}
}
}
]
这应该 return 只有最后一项。
你知道如何检索与用户不匹配的数据吗?
谢谢
编辑:
以下也不起作用:
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")]}}}])
根据答案,您可以更改
var ObjectId = require('mongodb'). ObjectID;
到
var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID;
我正在为 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 ],
}
}
}
]
这应该 return 只有最后一项。
你知道如何检索与用户不匹配的数据吗?
谢谢
编辑: 以下也不起作用:
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")]}}}])
根据答案
var ObjectId = require('mongodb'). ObjectID;
到
var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID;