MongoDB Helpful Queries

While doing the development everyones know that no one can remember all of the queries and commands. So in the blog I am covering most used Mongo DB queries.

Mongo DB - By Education Funda
Mongo DB Queries By Education Funda


Mongo DB Queries For Studio 3T and In Your Code

Fetch Queries:

db.getCollection("collectionName").find(
{ FILTER_COLUMN_NAME: 'VALUE' },
{ PROJECTION_COLUMN_NAME_1: 1, PROJECTION_COLUMN_NAME_2: 1 }
)

Get Duplicates Records

db.getCollection("collectionName").aggregate([
{"$group" : { "_id": "$DUP_COL_NAME", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$project": {"DUP_COL_NAME" : "$_id", "_id" : 0} }
])

Count Query

db.getCollection("collectionName").countDocuments(
{FILTER_COL_1:'VAL_1', FILTER_COL_2: 'VAL_2' }
)

Update Queries

db.getCollection("collectionName").updateMany(
{ FILTER_COL_1: { $in: ['VAL_1','VAL_2'] } },
{
$set: { UPDATE_COL_NAME: 'UPDATED_VAL' }
}
)

Rename Column Name of Document

db.getCollection("collectionName").updateMany(
{},//filter if required otherwise work for each docs
{
$rename: { 'CURRENT_COL_NAME': 'UPDATE_COL_NAME' }
}
)

Updated With Concat

db.getCollection("collectionName").updateMany(
{},
[{
$set: {
COLUMN_NAME: {
"$concat": [ "$COL_1", " - ", "$COL_2" ]
}
}
}]
)



Thanks for reading this blog, Please share your feedback in comments section.

Happy Coding </>

Comments

Popular posts from this blog

JavaScript Logical Output Based Interview Questions

Create and Deploy AWS SAM Application

Deploy Angular Build With Express JS Project