How to use aggregrate in mongodb to $match _id

时间:2015-09-30 23:20:48

标签: mongodb

Document:

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

This works:

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);
                    });
            });

This does not work:

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);
                    });
            });

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.

3 个答案:

答案 0 :(得分:23)

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

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

答案 1 :(得分:1)

尝试一下

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


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

答案 2 :(得分:-3)

使用toString()方法

const User = mongoose.model('User')
User.aggregate([
  {
    $match: { _id: user_id.toString()  }
  }
]