【问题标题】:MongoDB collection hyphenated nameMongoDB 集合连字符名称
【发布时间】:2014-09-02 22:01:37
【问题描述】:

我正在使用 Node.js 程序将数据插入 MongoDB 数据库。我已将数据插入名为“repl-failOver”的集合中。

var mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://localhost:30002/test", function(err, db) {
    if (err) throw err;
    db.collection("repl-failOver").insert( { "documentNumber" : document++}, function (err, doc) {
        if (err) throw err;
        console.log(doc);
    });
    db.close();
});

当我使用 Mongo shell 并使用 show collections 列出数据库中的集合时,我能够看到集合“repl-failOver”。

如何在 mongo shell 中为此集合运行查找命令?

【问题讨论】:

    标签: mongodb collections


    【解决方案1】:

    您在访问具有特定字符(-_)的集合时遇到此错误。我解释了解决方法here,但基本上你需要做的就是做

    db.getCollection("repl-failOver").insert(...)

    【讨论】:

      【解决方案2】:

      使用这个语法:

      db['repl-failOver'].find({})
      

      db.getCollection('repl-failOver').find({})
      

      您可以在手册的Executing Queries 部分找到更多信息:

      如果 mongo shell 不接受集合的名称,对于 如果名称包含空格、连字符或以 编号,您可以使用替代语法来引用集合,如 如下:

      db["3test"].find()
      
      db.getCollection("3test").find()
      

      【讨论】:

      • 第一个选项不适用于 MongoDB 3.4。第二个是工作!谢谢
      猜你喜欢
      • 1970-01-01
      • 2013-08-29
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多