How can I add a computed field using an arbitrary function with the Mongo aggregate structure?

I am using MongoDB Aggregate Framework . I have an existing field in each of my documents:

time: Date

And I want to create a new field timeBlockbased on a simple function:

var dateToTimeBlock = function(dateString, timeBlock){
    return new Date(dateString).valueOf() / timeBlock 
}

I understand that $ group can add fields , but the functions that are used to calculate these fields seem to be embedded in the mongo, for example $avg, $addetc. Is it possible to generate a calculated value based on an arbitrary field?

+4
source share
1 answer

- , MongoDB. JavaScript (, valueOf on Date object), Map-Reduce.

, Map-Reduce, .

, , .

, , , ( , ). $divide.

db.coll.aggregate([
    { $project : { dateToTime: { $divide : [ "$timeInt", timeBlock ] }}}
]);

, timeBlock - , :

db.coll.aggregate([
    { $project : { dateToTime: { $divide : [ "$timeInt", "$timeBlock" ] }}}
]);
+7

Source: https://habr.com/ru/post/1544909/


All Articles