【问题标题】:How do I print/use a specific value of a key in mongo shell script?如何在 mongo shell 脚本中打印/使用键的特定值?
【发布时间】:2023-02-26 01:08:58
【问题描述】:

我正在从 shell 运行以下命令;

const records = db.issues.find().limit(1);

print('Record:', records);
print('ID:', records.id);

它返回一条记录;

Record: [
  {
    _id: ObjectId("63f94e684902f564f7d418ca"),
    id: 1,
    status: 'New',
    owner: 'Ravan',
    effort: 5,
    created: ISODate("2019-01-15T00:00:00.000Z"),
    due: null,
    title: 'Error in console when clicking Add',
    description: 'Steps to recreate the problem:\n'
  }
]

所以我认为最后一行会产生;

ID: 1

它只是产生ID:,没有错误,我错过了什么?

下一个问题是,如果返回多条记录,我如何遍历游标?

干杯 C。

【问题讨论】:

    标签: node.js mongodb mongo-shell


    【解决方案1】:

    find() 方法返回一个游标,可以迭代该游标以检索每个文档。在您的示例中,records 是一个游标,它返回一个包含一个文档的数组。要打印/使用文档中键的特定值,您需要使用 dot notation 或括号表示法访问该值:

    print('ID:', records[0].id);
    

    遍历游标,可以使用forEach()(如果返回多条记录):

    const records = db.issues.find();
    
    records.forEach(function(record) {
      print('ID:', record.id);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2018-09-25
      • 1970-01-01
      • 2022-11-10
      • 2012-01-27
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      相关资源
      最近更新 更多