How to query MongoDB without switching to the database first - mongodb

When I connect to MongoDB from the command-line using the mongo command, I need to issue a use <db> command to switch to the appropriate database before I can run a query, like this:
[mongo#mongotest ~] $ mongo localhost:10001
MongoDB shell version: 2.4.6
connecting to: localhost:10001/test
> use mydb01
switched to db mydb01
Now I can run my query:
> db.records.find({"contact.name": "Jack"});
Is there a way to consolidate those commands into a single command? For example:
> mydb01.records.find({"contact.name": "Jack"});
The MongoDB shell documentation makes it seem like there should be a way, but I haven't been able to find it.

You can get a database object of another database than the one your are useing right now with db.getSiblingDB.
> db.getSiblingDB("mydb01").records.find({"contact.name": "Jack"});
You can also store that object in a variable. That way you can easily work with many databases simultaneously.
> var mydb01 = db.getSiblingDB("mydb01");
> mydb01.records.find({"contact.name": "Jack"});

Related

MongoDB and Batch script operation

I am trying to run MongoDB queries from batch script in windows...
I can not find any reference how to do that. Please can you show me some sample commands and one more question.
I am running this command for changing the database...
mongo --eval "use Sample_Test"
It does not work.
when I am inserting some data. It works, but, inserts in the default database, test.
mongo --eval "db.restaurants.insert({'Name':'Vishal'})"
I want to insert data in Sample_Test Database.
I only know above "mongo --eval" command, if anybody knows some more, please share it.....it would really help.
The data is getting inserted to default database as your use DB is not working here.
You need to add database name here using -d if you are using older version of MongoDB like following :
mongo -d Sample_Test --eval "db.restaurants.insert({'Name':'Vishal'})"
or you can execute any script file which contains all your mongo script like following:
mongo -d Sample_Test --eval mongoScript.js
In Mongo version 3.2, -d flag is not needed. For more information about script refer documentation
So you can simply use
mongo Sample_Test --eval "db.restaurants.insert({'Name':'Vishal'})"
Hope this will work for you.
use this code on place of your code:
mongo.exe Sample_Test --eval "db.restaurants.insert({'Name':'Vishal'})"
but if you want to run multiple commands in one session login use script file.
You can also use the URL style to connect to a MongoDb server and database like:
mongo "mongoldb://localhost:8000/myCars" --eval "db.getCollection('restaurants').insert({'Name':'Vishal'})
You can also put credentials into the URL.
See: https://docs.mongodb.com/manual/mongo/

Unable to get run js from command to query mongodb

Hi I am trying to run a simple JavaScript program to retrieve data from mongodb. collection named news.
var doc=db.news.findone();
printjson(doc);
I have mongodb running in my machine. when I try to run it from my command prompt, I am getting the below result.
MongoDB shell version:2.4.15-pre-
connecting to: test
I have no idea why it is connecting to test. Someone please help.
I assume, the collection, "news" resides on some mongo logical database, which need to be specified in script. For exmaple
db = db.getSiblingDB('db_name')
doc = db.news.findOne()
printjson(doc)
Then evaluate the script using
mongo --host ${host} --port ${port} script.js
If you don't specify a database in your connection string like for example,
//Connect to foo
${host}:${port}/foo
mongo will always try to connect to "test" database.

How to copy part of a collection from a remote server to a local database in MongoDB

I am new to MongoDB, so I'm probably just missing something simple. A remote server has a MongoDB database called DatabaseABC which has a collection called Logger. This collection is humongous. I figured the best way to understand how to query against it without having to wait several minutes between queries was to copy the last day's worth of documents in the collection locally.
From what I've read, I should be able to use cloneCollection and give it a query to filter it down. I can't get it to work. The documentation says,
You must connect directly to the mongod instance.
but I don't understand what that means. How do I connect to a local database using mongod? mongod seems like a way to start a database, I can do that, but I don't get how to run { cloneCollection: "DatabaseABC.Logger", from: "mongoDevEtc.domain.net:27017", query: { TheTimestamp: "2015-05-13" } } with it.
I need baby steps. Assume I have a local database called test. I have a fresh Microsoft Windows command prompt open pointed at the bin directory where mongod.exe exists. What commands do I enter in order to move all the logs written on May 13, 2015 from mongoDevEtc.domain.net:27017.DatabaseABC.Logger to my local collection at 127.0.0.1:21000.test.Logger (note, the logger collection doesn't exist locally yet)?
First of all mongod is the MongoDB server. It understands a bunch of different commands, but you need to use a client to issue those commands. The standard client for MongoDB is the Mongo Shell called mongo. You can invoke it directly from the command line and start issuing some commands.
Now, for your specific needs: the cloneCollection command allows you to copy from one collection in a DB on a distant server to an other collection, on a different DB on you local server (i.e.: the one to which your client is connected). From the Mongo Shell, you may issue this command (like any other "raw" command) using db.runCommand. Something like that:
> db.runCommand(
{ cloneCollection: "DatabaseABC.Logger",
from: "mongoDevEtc.domain.net:27017",
query: { TheTimestamp: "2015-05-13" }
}
)
Please note that is your distant db has the same name as your local db you might use the Mongo Shell database method db.cloneCollection instead:
> db.cloneCollection("mongoDevEtc.domain.net:27017",
"Logger",
{ TheTimestamp: "2015-05-13" })ΒΆ
As you can see below, db.cloneCollection is a simple wrapper around the cloneCollection database command:
> db.cloneCollection
function (from, collection, query) {
assert( isString(from) && from.length );
assert( isString(collection) && collection.length );
collection = this._name + "." + collection;
query = query || {};
return this._dbCommand( { cloneCollection:collection, from:from, query:query } );
}
To copy a database from a machine to your machine, fallow this steps:
Open the cmd
Run this code to copy:
mongodump --db Your_database_name /h IP_of_remote_machine
ex:
mongodump --db myDb /h 192.168.0.100
Run to restore the database from dump/myNpsCorporate to mongodb:
mongorestore --Your_database_name dump/Your_database_name
ex:
mongorestore --myDb dump/myDb
finish

mongo shell unusable, but access from my program is ok, after uninstalling/new install on OSX

all!
After uninstalling current stable (with brew), and installing the 2.4 rc2 (not brew, since brew --devel does not have it, but mainly as described here: http://shiftcommathree.com/articles/how-to-install-mongodb-on-os-x), even a couple of times, and perhaps being too eager to delete everything mongodb-related before the next install, I have ended up with this situation:
The Node-program I have that uses the database and works ok (find, insert and so on). But the problem is that the mongo shell does not work properly, I cannot insert or find documents. For example (now I have 2.4 rc2, but the situation was the same with the current stable):
$ mongo
MongoDB shell version: 2.4.0-rc2
connecting to: test
> show dbs
local 0.078125GB
> use mydb
switched to db mydb
> db.mydb.mycollection.insert = ({title: "O-oh, strange problem"})
{ "title" : "O-oh, strange problem" }
> show collections
> show dbs
local 0.078125GB
mydb (empty)
Then I do a insert via my Node-program and do this:
> show dbs
local 0.078125GB
mydb 0.203125GB
> use mydb
switched to db mydb
> show collections
mycollection
system.indexes
> db.mydb.mycollection.find()
>
Again, in my Node-program, 'find' finds what it should...
Any idea why mongo shell does not work?
Frode
You've got a collection called mydb.mycollection in a mydb database. It is unlikely that's really what you want. When you use a database from the shell, you are then able to reference the database via the db object without repeating the database name.
use mydb
# db is now implicitly the mydb database
# you no longer refer to it by name
db.mycollection.insert({"name" : "stacks overflowing"})
Also note that you were not calling the insert function, your code was attempting to set the function to the value of the new object.

How to load initial data in MongoDB?

Does anyone know how to populate mongodb with initial data? For example, with a traditional SQL database, you can put all your SQL statements in a textfile, then load that using a SQL command. This is extremely useful for unit testing.
Is it possible to do this with the mongo shell? For example, write down a list of shell statements into a file, and get the mongo shell to read the file and execute the statements.
./mongo server:27017/dbname --quiet my_commands.js
In my_commands.js:
db.users.insert({name:"john", email:"john#doe.com", age:12});
You can use the mongoimport tool that comes with MongoDB to import raw data.
To run scripts from a file, e.g. to recreate indexes, pass the file name as a command line argument:
mongo file.js "another file.js"