如何在MongoDB中使用聚合操作符$match与_id匹配

47

文档:

{
    "_id" : ObjectId("560c24b853b558856ef193a3"),
    "name" : "Karl Morrison",
    "pic" : "",
    "language" : ObjectId("560c24b853b558856ef193a2"),
    "cell" : 1,
    "local" : {
        "email" : "karl.morrison@instanty.se",
        "password" : "12345"
    },
    "sessions" : [
        {
            "id" : ObjectId("560c24b853b558856ef193a5")
        }
    ]
}

这有效:

yield new Promise(function (resolve, reject) {
                users.col.aggregate([
                        {
                            $match: {
                                'name': 'Karl Morrison'
                            }
                        }
                    ],
                    function (err, res) {
                        console.log('err ' + err);
                        console.log('res ' + JSON.stringify(res)); // <-- echos the object retrieved
                        if (err === null)
                            resolve(res);
                        reject(err);
                    });
            });

这个不起作用:

yield new Promise(function (resolve, reject) {
                users.col.aggregate([
                        {
                            $match: {
                                '_id': '560c24b853b558856ef193a3' // <-- _id of the user
                            }
                        }
                    ],
                    function (err, res) {
                        console.log('err ' + err);
                        console.log('res ' + JSON.stringify(res));
                        if (err === null)
                            resolve(res);
                        reject(err);
                    });
            });

.col 访问原生的mongodb对象(否则使用co-monk)。所以我现在正在手动进行。然而,这并不起作用。我怀疑我没有将id的hexstring转换为ObjectId。无论我尝试什么都不起作用。


1
_id 需要是 ObjectId。当与 .aggregate() 一起使用时,Monk 无法将类型从字符串转换为您,因此您需要自己转换类型。 - Blakes Seven
3
可能是 MongoDB - Aggregate $match on ObjectId 的重复问题。基本上原因相同,即“自己转换类型”,因为两个框架都使用类似的代码进行自动转换,但是这些代码都不适用于.aggregate() - Blakes Seven
@BlakesSeven 确实是这样,谢谢,我已经找了很久了(可能是由于mongoose的原因没有找到)。 - basickarl
4个回答

112
const ObjectId = mongoose.Types.ObjectId;
const User = mongoose.model('User')

User.aggregate([
  {
    $match: { _id: ObjectId('560c24b853b558856ef193a3') }
  }
])

16

试试这个

const User = require('User')
const mongoose = require("mongoose");


User.aggregate([
  {
    $match: { _id: new mongoose.Types.ObjectId('560c24b853b558856ef193a3') }
  }
])

为什么这里要用到'new'关键字?难道没有更好的方法吗? - undefined

0
你可以尝试在较旧的Mongos版本中使用$oid。
{ $match: { '_id' : {"$oid": '560c24b853b558856ef193a3' } } }
问候。

-5
const User = mongoose.model('User')
User.aggregate([
  {
    $match: { _id: new mongoose.Types.ObjectId('id') }
  }
])

1
这难道不是正确的做法的相反吗? - Miguel Péres

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接