How to insert a document with date in mongo?

The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to “example” Date now = new Date(); BasicDBObject timeNow = new BasicDBObject(“date”, now); example.insert(timeNow); If you are looking for a way to use the “server” time in operations, there is the $currentDate operator, but this works with “updates”, so … Read more

MongoDB aggregate within daily grouping [duplicate]

In Mongo 2.8 RC2 there is a new data aggregation operator: $dateToString which can be used to group by a day and simply have a “YYYY-MM-DD” in the result: Example from the documentation: db.sales.aggregate( [ { $project: { yearMonthDay: { $dateToString: { format: “%Y-%m-%d”, date: “$date” } }, time: { $dateToString: { format: “%H:%M:%S:%L”, date: … Read more

Mongodb, aggregate query with $lookup

For any particular person document, you can use the populate() function like var query = mongoose.model(“person”).find({ “name”: “foo” }).populate(“projects.tags”); And if you want to search for any persons that have any tag with ‘MongoDB’ or ‘Node JS’ for example, you can include the query option in the populate() function overload as: var query = mongoose.model(“person”).find({ … Read more

MongoDB $lookup on nested document

in this case there is required a nice play with $unwind and $project in aggregation framework please see below: db.alumni.aggregate([ {$match: {_id: ‘john’}}, {$unwind:”$items”}, {$unwind:”$items.items”}, {$lookup: { from: ‘schools’, localField: ‘items.items.school’, foreignField: ‘_id’, as: ‘schoolInfo’}}, {$unwind:”$schoolInfo”}, {$project:{ “_id”:1, “items”:[{ “name”:”$items.name”, “items”:[{ “school”:”$schoolInfo._id” , “grad”:”$items.items.grad” , “schoolInfo”:”$schoolInfo” }] }] }} ]).pretty() to see how it works … Read more