Mongo Query cheat Sheet
1. mongo -- start mongo shell
(By default, mongo looks
for a database server listening on port 27017 on the localhost interface.
To connect to a server on a different port or interface, use the --port and --host options.)
To connect to a server on a different port or interface, use the --port and --host options.)
2. List all the database
in mongo
show dbs
3. To create a new database
Use %database name%
(but the db hasn’t been created.Now insert some data into collection then it will show the data)
Use %database name%
(but the db hasn’t been created.Now insert some data into collection then it will show the data)
use test ( test
is the default name of the database which already exist in mongo )
5. To list all the tables(collections) within the same db .
show collections
6. To find a particular entry from the collection
db.%collection_name%.findOne()
db.testdata.findOne()
7. To find record with where statement and And
Db.%collection_name%.findOne({“key”:”value”,”key”:”value”})
Db.testdata.fineOne({“x”:2})
8. To get the count
Db.%collection_name%.findOne({“key”:”value”,”key”:”value”}).count()
Db.testdata.find().count()
Db.testdata.findOne({“x”:2,”x”:3}).count()
9.To insert multiple documents in mongo table
for (var i = 1; i <= 25; i++) db.%collection_name%.insert( { x : i } )
for (var i = 1; i <= 25; i++) db.testData.insert(
{ x : i } )
10. To insert single document in mongo table
db.%collection_name%.insert( { x : i } )
11. To copy from 1 collection to another
db.source.copyTo("target");
db.testdata.copyTo("testdata1");
(it will create a new collection with exact no of records
Because copyTo() uses eval internally, the copy operations will block all other operations on the mongod instance).
(it will create a new collection with exact no of records
Because copyTo() uses eval internally, the copy operations will block all other operations on the mongod instance).
12. Update single document in collection
db.%collection_name%.update( { “search_key” : “search_value”
}, { $set : { “update_key” : “update_value” } } )
db.testdata.update({“x”:2}),{$set:{“x”:”300”}})
13. Update Multiple documents in collection
Db%collection.name%.update({"search_key":"search_value"},{$set:{"update_key":"update_value"}},{"multi":true})
db.testdata.update({"x":3},{"x":"200"}},{"multi":true})
14. Delete document(records) from collection
db.%collection_name%.remove( { “search_key” : “search_value”
} )
db.testdata.remove({"x":2,"x1":100});
15. List all index for a database
db.system.indexes.find()
16 . List all index in collection
db.testdata.getIndexes()
No comments:
Post a Comment