MongoDB 集合连字符名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24711939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB collection hyphenated name
提问by Subramanian
I'm using Node.js program to insert data into a MongoDB database. I have inserted data into a collection named "repl-failOver".
我正在使用 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();
});
When I use the Mongo shell and list down the collections in the database using show collections
I am able to see the collection "repl-failOver".
当我使用 Mongo shell 并使用show collections
我列出数据库中的集合时,我能够看到集合“repl-failOver”。
How do I run a find command from the mongo shell for this collection?
如何从 mongo shell 为这个集合运行 find 命令?
回答by Gergo Erdosi
Use this syntax:
使用以下语法:
db['repl-failOver'].find({})
or
或者
db.getCollection('repl-failOver').find({})
You can find more information in the Executing Queriessection of the manual:
您可以在手册的“执行查询”部分找到更多信息:
If the mongo shell does not accept the name of the collection, for instance if the name contains a space, hyphen, or starts with a number, you can use an alternate syntax to refer to the collection, as in the following:
db["3test"].find() db.getCollection("3test").find()
如果 mongo shell 不接受集合的名称,例如如果名称包含空格、连字符或以数字开头,则可以使用替代语法来引用集合,如下所示:
db["3test"].find() db.getCollection("3test").find()
回答by Salvador Dali
You are getting this error from accessing collections with specific characters (-
, _
, ). I explained the workaround here, but basically all you need is to do
您在访问具有特定字符 ( -
, _
, ) 的集合时会收到此错误。我在这里解释了解决方法,但基本上你需要做的就是
db.getCollection("repl-failOver").insert(...)
db.getCollection("repl-failOver").insert(...)