Mongodb – Mongo cannot find the collection

mongodb

My mongodb server has a database named villageContents

It has a collection named tablebusiness

If I run mongo I saw

MongoDB shell version: 2.0.7
connecting to: test
>

I wonder what "test" is. There is no database named test there.

I tried to execute

> villageContents.tablebusiness.ensureIndex({"LatitudeLongitude" : "2d"})
Wed Aug 15 09:28:28 ReferenceError:is not defined (shell):1
>

I tried to execute

> test.villageContents.tablebusiness.ensureIndex({"LatitudeLongitude" : "2d"})
Wed Aug 15 09:29:13 ReferenceError: test is not defined (shell):1
>

What did I do wrong?

Then I did

db.villageContents.tablebusiness.ensureIndex({"LatitudeLongitude" : "2d"})

Nothing shows up. Indexes aren't even added.

So what's wrong?

Best Answer

I wonder what "test" is. There is no database named test there.

This is just the default database that the mongo shell uses when it connects, unless you insert something, it is empty. You can do this with any database in fact, test is just the default.

The first command will not work because you did not prefix it with db, as such it attempts to find "isikota" as a variable (javascript) and fails to find it. Similarly your next attempt does the same with a non-existent "test" variable.

Finally, this command is the right form (prefixed with db):

db.isikota.tablebusiness.ensureIndex({"LatitudeLongitude" : "2d"})

But, you did not change database (with use <database name>) or at least you did not mention trying to at least. What this is going to do is create a 2d (geoindex) index on a "LatitudeLongitude" field on a collection named "isikota.tablebusiness" in the test database (db always refers to the database you are currently using). Even if this collection does not exist, the index will be created (this is just an insert into the system.indexes namespace) and hence the command succeeds. You just won't see anything else, because I believe you are still operating on the test database.

Assuming your data is actually in a database called "isikota" and that "tablebusiness" is your collection, what you actually want to do is this:

use isikota;
db.tablebusiness.ensureIndex({"LatitudeLongitude" : "2d"});

That will create the index on the "LatitudeLongitude" field in a collection named "tablebusiness" in a database named "isikota".