【问题标题】:Access query fields in mongodb inside forEach在forEach里面访问mongodb中的查询字段
【发布时间】:2020-05-12 22:50:14
【问题描述】:

在 mongodb 中,我们可以在 find() 方法上使用 forEach() 来迭代集合内的文档。现在的问题是我们能否访问 forEach 中的查询字段。例如:-

db.mycollection.find({name : 'Mike'}).forEach(function(document) {
    // var firstName = name;
})

我们可以做这样的事情或者我们可以使用什么替代方案?请帮忙。

【问题讨论】:

  • find 方法返回一个游标。 forEach 遍历 find 方法返回的文档。例如,document 变量可用于打印到控制台:printjson(document) 访问字段:let doc_id = document._id。这些适用于从mongo shell 运行的查询。

标签: json mongodb mongodb-query mongojs


【解决方案1】:

你快到了,试试下面的代码:

db.mycollection.find({name : 'Mike'}).forEach(function(document) {
    var firstName = document.name; // Just use the . operator
    print(firsName)
    // Rest of your operations.
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多