简体   繁体   English

聚合匹配管道不等于MongoDB

[英]Aggregate match pipeline not equal to in MongoDB

I am working on an aggregate pipeline for MongoDB, and I am trying to retrieve items where the user is not equal to a variable. 我正在为MongoDB的聚合管道工作,我正在尝试检索用户不等于变量的项目。

For some reason, I couldn't make it work. 出于某种原因,我无法使其发挥作用。 I tried to use $not , $ne and $nin in different possible way but can't make it to work. 我尝试以不同的方式使用$not$ne$nin ,但无法使其工作。

This is how it looks like: 这是它的样子:

Data sample: 数据样本:

[{
    "_id": { "$oid": "565674e2e4b030fba33d8fdc" },
    "user": { "$oid": "565674832b85ce78732b7529" }
}, {
    "_id": { "$oid": "565674e2e4b030fba33d8fdc" },
    "user": { "$oid": "565674832b85ce78732b7529" }
}, {
    "_id": { "$oid": "565674e2e4b030fba33d8fdc" },
    "user": { "$oid": "56f9dfc5cc03ec883f7675d0" }
}]

Pipeline sample (simplified for this question): 管道样本(针对此问题进行了简化):

Where req.query.user.id = "565674832b85ce78732b7529" req.query.user.id = "565674832b85ce78732b7529"

collection.aggregate([
    {
        $match: {
            user: {
                $nin: [ req.query.user.id ],
            }
        }
    }
]

This should return only the last item. 这应该只返回最后一项。

Do you have any idea how to retrieve the data that doesn't match the user? 您是否知道如何检索与用户不匹配的数据?

Thanks 谢谢

Edit: The following doesn't work either: 编辑:以下不起作用:

collection.aggregate([
    {
        $match: {
            'user.$oid': {
                $nin: [ req.query.user.id ],
            }
        }
    }
]);

I also tried with ObjectID() and mongodb complains: [MongoError: Argument must be a string] 我也试过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);
    });
});

But this line works in the shell: 但这行在shell中有效:

db.collection.aggregate([{$match:{"user":{"$nin":[ObjectId("565674832b85ce78732b7529")]}}}])

Based on the answer here , you can change 根据这里的答案,你可以改变

var ObjectId = require('mongodb'). ObjectID;

to

var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM