Sunday 22 September 2019

MongoDB Interview Question And Answers for 1 Year Experience

MongoDB Interview Question And Answers for 1 Year Experience

Question: How do I query mongodb with like ?
Following are few example of like as compare to SQL Query
/*select * from users where name like "%B%";*/
db.users.find({name: /B/});

/*select * from users where name like "B%"; */
db.users.find({name: /^B/});

/*select * from users where name like "%B"; */
db.users.find({name: /B$/});



Question: How to execute case in sensitive query?
/*select * from users where name like "%B%" OR like "%b%"; */
db.users.find({name: /b/i});



Question: How to list all collections in the mongoDB?
Following are three different methods.
db.getCollectionNames()

show collections

show tables




Question: Pretty print in MongoDB shell?
Normally we use query as below:
db.users.find()

For Pretty display, use like below:
db.users.find().pretty()




Question: How to get the last N records?
db.users.find().sort({_id:-1}).limit(20);
/* -1 means descending order */




Question: How to export collection into CSV?
mongoexport --host localhost --db bank --collection users --csv --out e:/dump/mycsv.csv --fields name,age,gender



Question: How to import into collection from CSV?
mongoimport -d bank -c users --type csv --file e:/dump/mycsv.csv --headerline



Question: How can I rename a field for all documents in MongoDB?
db.students.updateMany( {}, { $rename: { "name": "full_name" } } )



Question: How to store date/time in mongodb
db.users.insert({date: ISODate("2014-02-10T10:50:42.389Z")})