Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB collection hyphenated name

I'm using Node.js program to insert data into a MongoDB database. I have inserted data into a collection named "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".

How do I run a find command from the mongo shell for this collection?

like image 297
Subramanian Avatar asked Jul 12 '14 10:07

Subramanian


People also ask

How are collections named in MongoDB?

The general conventions are: Lowercase names: this avoids case sensitivity issues, as MongoDB collection names are case sensitive. Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"

How do I change collection name in MongoDB?

In MongoDB, you can use the renameCollection() method to rename or change the name of an existing collection. The new name of the collection. Optional, if true then mongod drops the target of renameCollection former to renaming the collection. The default value is false.

Can a MongoDB have multiple collections?

As mentioned above, a single database can have multiple collections. The following creates multiple collections. Use the show collections commands to list all the collections in a database. To delete a collection, use the db.

How do I create a collection name in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().


2 Answers

Use this syntax:

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

or

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

You can find more information in the Executing Queries section 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() 
like image 164
Gergo Erdosi Avatar answered Oct 09 '22 00:10

Gergo Erdosi


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(...)

like image 21
Salvador Dali Avatar answered Oct 08 '22 23:10

Salvador Dali