programing

mongodb에서 aggregate를 $match_id로 사용하는 방법

linuxpc 2023. 5. 11. 21:08
반응형

mongodb에서 aggregate를 $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 개체에 액세스합니다(다른 경우에는 공동 사용).그래서 수동으로 하고 있습니다.하지만 이것은 작동하지 않습니다.ID 16진수 문자열을 ObjectId에 캐스팅하지 않은 것 같습니다.무슨 짓을 해도 소용이 없어요.

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

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

사용해 보세요.

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


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

toString() 메서드를 사용합니다.

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

언급URL : https://stackoverflow.com/questions/32877064/how-to-use-aggregrate-in-mongodb-to-match-id

반응형