MongoDB collection hyphenated name

MongodbCollections

Mongodb Problem Overview


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?

Mongodb Solutions


Solution 1 - Mongodb

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

Solution 2 - Mongodb

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSubramanianView Question on Stackoverflow
Solution 1 - MongodbGergo ErdosiView Answer on Stackoverflow
Solution 2 - MongodbSalvador DaliView Answer on Stackoverflow