如何在mongodb中使用aggregrate来$ match _id [英] How to use aggregrate in mongodb to $match _id

查看:116
本文介绍了如何在mongodb中使用aggregrate来$ match _id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档:

{
    "_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十六进制字符串强制转换为ObjectId.不管我尝试什么,都行不通.

The .col access the native mongodb object (using co-monk otherwise). So I'm doing it manually. This however isn't working. I suspect I am not casting the id hexstring to an ObjectId. No matter what I try nothing works.

推荐答案

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

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

这篇关于如何在mongodb中使用aggregrate来$ match _id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆