【问题标题】:Aggregate match pipeline not equal to in MongoDB聚合匹配管道不等于 MongoDB
【发布时间】:2016-10-07 06:06:52
【问题描述】:

我正在为 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")]}}}])

【问题讨论】:

  • 您在查询中缺少“$oid”。所以在使用的查询中尝试“user.$oid”而不是用户。
  • 您是否使用某种自定义的_id 字段,而不是Mongo 的ObjectId 实例?通常在查询ObjectId-like 字段时必须$nin: [ ObjectId(req.query.user.id) ]
  • 我使用waterline (sailsjs.org/documentation/reference/waterline-orm) 自动生成那些id
  • mongodb 不允许键名以 $ 开头你如何用 "$oid" 保存数据?

标签: javascript node.js mongodb sails.js waterline


【解决方案1】:

根据here的回答,可以改

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

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

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多