You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// to avoid timeout use "noCursorTimeout" method when db has lots & lots of records
db.getCollection('EmployeeDetail').find({}).noCursorTimeout().forEach(function (record) {
print("Name: " + record.Name)
})
Convert objectId to string Id
db.getCollection('EmployeeDetail').find({}).forEach(function (record) {
var objectId = record._id;
record._id = record._id.valueOf();
if (typeof objectId === 'object') {
// duplicate same record with string type id
db.getCollection('EmployeeDetail').insert(record);
// remove old record with object type id
db.getCollection('EmployeeDetail').remove({
_id: objectId
});
print("Name: " + record.Name)
}
})
Group example
db.getCollection('EmployeeDetail').aggregate(
[{
$group: {
// group by field name Mobile
_id: "$Mobile",
count: {
$sum: 1
}
}
}, {
$match: {
count: {
$gt: 1
}
}
}]
);
db.getCollection('EmployeeDetail').aggregate(
[{
$group: {
// group by field name Mobile
_id: "$Mobile",
// return additional field information of Name, Salary
Name: {
$addToSet: "$Name"
},
Salary: {
$addToSet: "$Salary"
},
count: {
$sum: 1
}
}
}, {
$match: {
count: {
$gt: 1
}
}
}]
);
// Add or update field
db.getCollection('EmployeeDetail').update({
"Name": "A"
}, {
$set: {
Age: NumberInt(18)
}
}, {
upsert: false,
multi: true
})
// Remove field
db.getCollection('EmployeeDetail').update({
"Mobile": "123"
}, {
$unset: {
Age: 1
}
}, {
upsert: false,
multi: true
})
//upsert: If set to true, creates a new document when no document matches the query criteria. The default value is false
// multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false
Sort Rows
// Sort all the rows
db.getCollection('EmployeeDetail').find({}).sort({
$natural: -1
})
// Sort by salary field
db.getCollection('EmployeeDetail').find({}).sort({
"Salary": 1
})
Array Queries
// Return all where Department Name is D5
db.getCollection('EmployeeDetail').find({
"Department.Name": "D5"
})
// Return all where Department field is null
db.getCollection('EmployeeDetail').find({
Department: null
})
// Return all where Department array size is 0
db.getCollection('EmployeeDetail').find({
Department: {
$size: 0
}
});