MongoDB query

Posted under » MongoDB on 7 Jan 2023

We have learnt how to insert a document and show all the documents in a collection.

To make a query fast, we will index into RAM. Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents.

Indexing, will make searching more efficient.

anodb> db.users.createIndex({name:1,likes:1}) # double index
anodb> db.users.createIndex({"name" : 1})

However, if you want unique and no duplicates records. Also we create an Index on an Embedded Field in an Array.

anodb> db.psystuque.createIndex({"diagnostic05b1.qid" : 1},{unique: true})

Do not do a double index because you can still have duplicates provided it doesn't satisfy both indexed fields.

To show indexes

anodb> db.users.getIndexes()

To drop indexes

anodb> db.users.dropIndex( "nameIdx" )

Although I also create an index for likes, I only use the name column. Let us refine the results. Let's say I just want to see the name column.

anodb> db.users.find({name:"Lee"},{name:1,_id:0})
// or 
anodb> db.users.find({name:"Lee"},{likes:0,_id:0})
[ { name: 'Lee' } ]

If I want to find other people than Lee,

anodb> db.users.find({name: { $ne : "Lee"}},{likes:0,_id:0})

If you want to find Lee OR Goh. If you prefer $and do the same.

anodb> db.users.find({$or: [{name: "Lee"},{name: 'Goh'}]})

If you want to find something in an embedded object.

anodb> db.mth.find({name: {'que.log': 67484}})

This is quite a powerful feature. Searching in an array is so easy. Which is good for tags or keyword.

anodb> db.hardware.find({subtype: 'SSD' })

If you want to see all people and everything

anodb> db.users.find({},{likes:0,_id:0})

You use regex for a like filter.

mth> db.students.find({date_joined: { $regex: '2024' }})

For numbers. Eg. greater than or equal

mth> db.students.find({age: { $gte: 18 }})

If value is None

mth> db.students.find({date_joined: null })

To sort

mth> db.students.find({}).sort({cid:1, username: -1})
Where username is sorted in descending order.

By default you will only see 20 rows. Assuming you want to see 200 rows instead.

config.set( "displayBatchSize", 200 )

mooooore »

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data