MongoDB Usefull Queries

Usefull MongoDB Queries

Tolga Çelik
1 min readApr 8, 2021

I am going to share some of usefull mongo database queries

  • Collection name in query
db.getCollection('your_collection')
db.your_collection.
  • For more readible of the result of your query.
db.items.find({}).pretty()
  • Searching multiple values in a column
db.getCollection('your_collection').find({
_id: { $in: [
“044566” ,
“1212121”
]}
})
  • The field is not equal to the specified value
db.your_collection.find( { field_name: { $ne: 20 } } )
  • The value is higher/bigger than given size using $size or $where
db.your_collection.find( { field_name: { $size: 2 } } );ORdb.your_collection.find(
{$where: "this.field_name.length > 40"}
)
.limit(2); //if you want to get only limited recors.
  • To check if the field is not empty ( fields is exists).
db.your_collection.find({field_name: {$exists: true}). if your field is an array , then you can choose "field.index"db.your_collection.find({'field_name.1': {$exists: true}})

to combine both query you can use for if field is not empty and bigger than 30

db.your_collection.find(
{field_name: {$exists: true},
$where: "this.field_name.length > 30"}
);

These are just the beggining. The rest will come soon. So keep following ;)

--

--