Simple join query

Data set:

db.createCollection(“employee”);
db.employee.insert(
{
_id: 1,
name: { first: ‘John’, last: ‘Backus’ },
city: ‘New York’,
department:1
}
);

db.employee.insert(
{
_id: 2,
name: { first: ‘Merry’, last: ‘Desuja’ },
city: ‘London’,
department:2
}
);
db.createCollection(“department”);
db.department.insert(
{
_id: 1,
department: ‘Manager’
}
);

db.department.insert(
{
_id: 2,
department: ‘Accountant’
}
);

Join Query on department field:

function addDepartmentInEmployee(){
db.department.find().forEach(function(obj){
var id=obj._id.valueOf();
var id1=obj.department;
print(id);
db.employee.update({department:id}, {$set:{“post”:id1}});
});
}
addDepartmentInEmployee();

create collection a new collection by grouping data in mongodb

Group the collection collectionName by author and count them, then insert the result into collection newCollectionName

db.createCollection(“newCollectionName”);
var doc=
db.collectionName.aggregate(
{ $group : {
_id : “$author”,
countB : { $sum : 1 }
}}
);
db.newCollectionName.insert(doc.result);

 

Another example, count by date

db.createCollection(“newCollectionName”);
db.newCollectionName.insert(
db.collectionName.group(
{
keyf: function(doc) {
var date = new Date(doc.date);
var dateKey = date.getFullYear()+”-“+(date.getMonth()+1)+”-“+date.getDate()+”;
return {‘day’:dateKey};
},
cond: {},
initial: {count:0},
reduce: function(obj, prev) {prev.count++;}
}).result
);