如何在mongodb中使用聚合到$ match _id

Kar*_*son 12 mongodb

文献:

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

这有效:

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);
                    });
            });
Run Code Online (Sandbox Code Playgroud)

这不起作用:

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);
                    });
            });
Run Code Online (Sandbox Code Playgroud)

.col访问本地mongodb的对象(使用共僧以其他方式).所以我是手动完成的.然而,这不起作用.我怀疑我没有将id hexstring转换为ObjectId.无论我尝试什么都行不通.

Raf*_*yng 30

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

User.aggregate([
  {
    $match: { _id: ObjectId('560c24b853b558856ef193a3') }
  }
])
Run Code Online (Sandbox Code Playgroud)

  • 谢谢一群人。**mongoose.Types.ObjectId** 救了我的命。 (6认同)

小智 5

尝试这个

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


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