【问题标题】:How to get a string in ObjectId in MongoDB v3.6?如何在 MongoDB v3.6 中获取 ObjectId 中的字符串?
【发布时间】:2023-02-14 13:19:00
【问题描述】:

我有一个聚合查询,其 MongoDB 响应是:

_id: ObjectId('5e822d6c87502b3a9b751786')

我想获取 ObjectId 中的字符串,即 5e822d6c87502b3a9b751786


[ 问题 ]

我已经搜索过这个问题,但到目前为止只有三个运算符能够做到这一点,即$toString$toObjectId$convert

$project: {
      _id: {
        $toString: "$_id"
      }
}
$project: {
      _id: {
        $toObjectId: "$_id"
      }
}
$project: {
      _id: {
        $convert: {
          input: "$_id"
          to: "string"
        }
      }
}

MongoDB v3.6 不支持它们如果我没有记错的话。 MongoDB v3.6 中是否有任何解决方法来获取 ObjectId 中的字符串?

任何帮助深表感谢 :)

【问题讨论】:

标签: mongodb aggregation-framework


【解决方案1】:

对于 MongoDB v3.6,$toString$convert 在 v4.0 之前不可用,您可能需要求助于 JS/应用程序级别访问 _id

db.testCollection.insertMany([
{
    "_id": ObjectId("5e822d6c87502b3a9b751786")
}]);

db.testCollection.find().forEach( doc => { 
    // put your logic for process here
    console.log(JSON.stringify(doc._id))
});

输出:

"5e822d6c87502b3a9b751786"

【讨论】:

    【解决方案2】:

    只是想在一些发现之后添加ray's answer

    定义了一个模型在应用程序中,这里有一些对我有用的解决方法:

    1. 承诺
      const TestCollection = require('../models/testCollection');
      
      function getStringInObjectId() {
        TestCollection.find().then(t => {
          t.forEach(doc => {
            // Put some logic here...
            console.log('string in ObjectId :', JSON.stringify(doc._id));
          });
        });
      }
      
      1. 异步/等待
      const TestCollection = require('../models/testCollection');
      
      async function getStringInObjectId() {
        const t = await TestCollection.find();
        t.forEach(doc => {
          // Put some logic here...
          console.log('string in ObjectId :', JSON.stringify(doc._id));
        });
      }
      

      聚合也是如此:

      1. 承诺
        const TestCollection = require('../models/testCollection');
        
        function getStringInObjectId() {
          TestCollection.aggregate([
            { $match: { 'name': 'marc' } }, // <- { 'name': 'marc' } is just an example, feel free to change it
            // Put some stages here if required...
          ]).then(t => {
            console.log('string in ObjectId : ', t[0]._id.toString());
          });
        }
        
        1. 异步/等待
        const TestCollection = require('../models/testCollection');
        
        async function getStringInObjectId() {
          const t = await TestCollection.aggregate([
            { $match: { 'name': 'marc' } }, // <- { 'name': 'marc' } is just an example, feel free to change it
            // Put some stages here if required...
          ]);
          console.log('string in ObjectId : ', t[0]._id.toString());
        }
        

        JSON.stringify()toString() 可用于将其转换为字符串。随意更正变量名。

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2011-12-11
      • 2018-11-09
      • 2016-07-03
      • 2022-10-21
      • 2022-01-02
      相关资源
      最近更新 更多