MongoDB gets every second result

In MongoDB, all documents have a date field, this is a timestamp.

There is a lot of data, and I want to get only part of it for each interval:

eg. 400ms

1402093316030<---- 1402093316123 1402093316223 1402093316400<---- 1402093316520 1402093316630 1402093316824<---- 

Is it possible to get every other or every third result? Or is it better to have the first document every 400 ms?

+3
source share
1 answer

You can do this with an aggregation structure and a little math. Say you have a "timestamp" field and additional fields "a", "b" and "c":

 db.collection.aggregate([ { "$group": { "_id": { "$subtract": [ "$timestamp", { "$mod": [ "$timestamp", 400 ] } ] }, "timestamp": { "$first": "$timestamp" }, "a": { "$first": "$a" }, "b": { "$first": "$b" }, "c": { "$first": "$c" } }} ]) 

Thus, the mathematical date there โ€œgroupsโ€ according to the values โ€‹โ€‹of the โ€œtimestampโ€ field with an interval of 400 ms. The rest of the data is identified using the $first operator, which selects the "last" value from the field as shown at these grouping boundaries.

If you otherwise ran the "last" element at these boundaries, you switch to using the $last statement.

The end result is the last document that occurred every 400 millisecond interval.

See the aggregate command and Aggregate Structure Operators for more reference.

+4
source

All Articles