how to output the result to a file in monogodb - mongodb

I wan to list all database in Monogodb and output to a txt file, but it did not work.
mongo 127.0.0.1/test -eval 'var c= show databases;' >>db_list.txt
the error message is
MongoDB shell version: 2.6.12
connecting to: 127.0.0.1/test
2016-12-06T12:12:32.456-0700 SyntaxError: Unexpected identifier
anyone knows how to make this work. I appreciate any help.

To use eval and list databases directly on a shell, the following query should be helpful.
mongo test --eval "printjson(db.adminCommand('listDatabases'))"
MongoDB shell version: 3.2.10
connecting to: test
{
"databases" : [
{
"name" : "local",
"sizeOnDisk" : 73728,
"empty" : false
},
{
"name" : "m034",
"sizeOnDisk" : 11911168,
"empty" : false
},
{
"name" : "test",
"sizeOnDisk" : 536576,
"empty" : false
}
],
"totalSize" : 12521472,
"ok" : 1
}
This will list all the collection names in a particular DB.
mongo test --eval "printjson(db.getCollectionNames())"
MongoDB shell version: 3.2.10
connecting to: test
[
"aaa",
"areamodel",
"email",
"hex",
"key",
"mel",
"multi",
"ques",
"rich"
]
A sample execution for reference (screenshot)

Instead of test you can go simply,
mongo db_name query.js > out.json
here query.js contains any query like:
printjson( db.adminCommand('listDatabases') )

Related

Connect to Mongo Atlas Secondary

On Cloud Mongo (Mongo Atlas) Free tier, it has 3 members of servers. How can I connect to the Secondary host from Mongo shell? Their example only shows how to connect to Primary.
"members" : [
{
"_id" : 0,
"name" : "***-shard-00-00-***.mongodb.net:27017",
....
},
{
"_id" : 1,
"name" : "***-shard-00-01-***.mongodb.net:27017",
.....
},
{
"_id" : 2,
"name" : "***-shard-00-02-***.mongodb.net:27017",
.....
}
]
You need to use the --ssl flag and specify authSource.
Try:
mongo "mongodb://***-shard-00-02-***.mongodb.net:27017/?authSource=admin" --ssl
at the very minimum. Of course you can add options for username, password, database to connect, etc...
mongo "mongodb://<username>:<password>#***-shard-00-02-***.mongodb.net:27017/<database>?authSource=admin" --ssl
I hope this helps.

Access document directly by ID

I'm used to working with firebase where I can access a document directly by fetching data from the db like so.
db.collection('collectionName/documentID').get();
I can't seem to find any documentation regarding doing something similar in mongodb. Do I have to use a find query to grab data from a mongodb or have I missed something? Thanks
I'm thinking
const collection = db.collection('collectionName');
collection.findOne({_id: ObjectId('documentID'); });
Since mongo consolse is an interactive javascript shell, One way would be to create a method similar to this:
function collectionNameGet(idToFind) {
return db.collection.find({_id: idToFind });
}
In the mongo shell you can directly get it as below:
db.st4.find({"_id" : "1234"})
Result set:
{ "_id" : "1234", "raw" : { "meas" : { "meas1" : { "data" : "blabla" }, "mesa2" : { "data" : "foo" } } } }
Or by default mongo id as:
db.st1.find({"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4")})
{ "_id" : ObjectId("5c578d57ce9ba4a066ca2fa4"), "name" : "Just a name", "users" : [ "user1", "user2" ] }
For display the result in pretty format
db.st1.find({"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4")}).pretty()
Result set:
{
"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4"),
"name" : "Just a name",
"users" : [
"user1",
"user2"
]
}
Here st4 is my collection name in the database test, so once you are on mongo shell do the below steps before above query:
use test
db.st1.insert({"name" : "Just a name", "users" : [ "user1", "user2" ] })
and then you can query by default _id generated mongo, you can simply make a query to get the recently added documents in the collection st1 as below:
db.st1.find().sort({_id:-1}).limit(1)
Hope this will help you out to do some basic query on mongo shell

Mongo Db query inside array of object and update

Ok my schema structure is:
"labTest" : [
{
"_id" : ObjectId("56eaab35b5f57f2c1b022b00"),
"test" : "Blood Test"
},
{
"_id" : ObjectId("56eaab35b5f57f2c1b022aff"),
"test" : "Urine Test"
},
{
"_id" : ObjectId("56eaab35b5f57f2c1b022afe"),
"test" : "ECG"
}
],
Now I have the id and test field to this schema, I just want to query and add a status field inside this schema and make it 1.
Any help will be very appreciated
You can do this using commandline very easily. I am considering that your environment is all set. simply type following command in your commandline interface.
db.yourschemaname.update({},{$set:{"status":1}},{multi:true});

How to do custom mapping using mongo connector with elasticsearch

I wanna connect mongodb and elasticsearch. I used mongo connector to connect them. I followed instruction from below link to setup==>
http://vi3k6i5.blogspot.in/2014/12/using-elastic-search-with-mongodb.html
I am able to connect mongodb and elasticsearch. But by default mongo connector created indices in elasticsearch for all databases of mongodb.
I want to create only one index for my one database and I want to insert only selected field of documents. for example: in mongo shell==>
use hotels
db.restaurants.insert(
{
"address" : {
"street" : "2 Avenue",
"zipcode" : "10075",
"building" : "1480",
"coord" : [ -73.9557413, 40.7720266 ],
},
"borough" : "Manhattan",
"cuisine" : "Italian",
"grades" : [
{
"date" : ISODate("2014-10-01T00:00:00Z"),
"grade" : "A",
"score" : 11
},
{
"date" : ISODate("2014-01-16T00:00:00Z"),
"grade" : "B",
"score" : 17
}
],
"name" : "Vella",
"restaurant_id" : "41704620"
}
)
This will create database hotels and collection restaurants. Now I want to create index and I want to put only address field in elasticsearch for that index.
Below are the steps what I tried but thats not working :
First I start mongo connector like below :
Imomadmins-MacBook-Pro:~ jayant$ mongo-connector -m localhost:27017 -t localhost:9200 -d elastic_doc_manager --oplog-ts oplogstatus.txt
Logging to mongo-connector.log.
Then from new shell tab, I made command like :
curl -XPUT 'http://localhost:9200/hotels.restaurants/'
curl -XPUT "http://localhost:9200/hotels.restaurants/string/_mapping" - d'{
"string": {
"properties" : {
"address" : {"type" : "string"}
}
}
}'
But only index is created in elasticsearch named as hotels.restaurants. I can't see any document for index hotels.restaurants.
Please suggest me how to add document for hotels.restaurants
Well I got an answer to my question, while starting mongo connector we can specify collection name and the list of fields we are interested in. Please check below command ==>
$ mongo-connector -m localhost:27017 -t localhost:9200 -d elastic_doc_manager --oplog-ts oplogstatus.txt --namespace-set hotels.restaurants --fields address,grades,name

mongo - how to query a nested json

I am a complete mongo newbie. I am using mongo hub for mac. I need to query the for following json -
{ "_id" : ObjectId( "abcd" ),
"className" : "com.myUser",
"reg" : 12345,
"test" : [
{ "className" : "com.abc",
"testid" : "pqrs" } ] }
and find records where testid is pqrs. How would I go about doing that?
You can type {'test.testid': 'pqrs'} in the query field of Mongo Hub.
Looks like test is an array. If you are expecting multiple values in array you can do -
"test": {
"$elemMatch": {
"testid": "pqrs",
}
}