【问题标题】:Loop through Mongo collections and execute query [duplicate]循环遍历 Mongo 集合并执行查询 [重复]
【发布时间】:2023-03-22 04:38:01
【问题描述】:

我正在尝试在我的数据库中打印每个集合的第一个文档。我有以下脚本:

var collectionNames = db.getCollectionNames();
for(var i = 0, len = collectionNames.length; i < len ; i++){
    db[collectionNames[i]].findOne() //find[0]
}

我看不出我的逻辑中的错误在哪里,但此代码仅打印最新集合中的第一个文档

【问题讨论】:

    标签: mongodb mongo-shell


    【解决方案1】:

    说我们有

    > db.test1.save({item: 1})
    WriteResult({ "nInserted" : 1 })
    > db.test1.save({item: 2})
    WriteResult({ "nInserted" : 1 })
    > db.test1.save({item: 3})
    WriteResult({ "nInserted" : 1 })
    > db.test2.save({item: 3})
    WriteResult({ "nInserted" : 1 })
    > db.test2.save({item: 4})
    WriteResult({ "nInserted" : 1 })
    

    然后我们就可以运行了:

    >var docs = [];
    >
    > collectionNames.forEach(function(name){
    ... docs.push(db[name].findOne());
    ... });
    

    然后我们就可以打印文档了

    > docs
    [
            {
                    "_id" : ObjectId("59fc9754cb24a8fbf29c6d5a"),
                    "item" : 1
            },
            {
                    "_id" : ObjectId("59fc9762cb24a8fbf29c6d5d"),
                    "item" : 3
            }
    ]
    

    db[collectionNames[i]].findOne() 在您的示例中不起作用的原因是您对返回值没有做任何事情。

    【讨论】:

      猜你喜欢
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2018-06-16
      • 2016-07-16
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多