Answer the question
In order to leave comments, you need to log in
MongoDB: fetching latest values
Good afternoon.
Once a second, the data that comes in is written to MongoDB, in this format:
{
'_id' : 1,
'info': [ 'c':768, 'd':345 ]
}
{
'_id' : 2,
'info': [ 'e':333 ]
}
{
'_id' : 3,
'info': [ 'c':353, 'e':113 ]
}
[ 'c':353, 'e':113, 'd':345 ]
Answer the question
In order to leave comments, you need to log in
In general, with this structure:
{
"_id" : 3,
"info" : [
{
"k" : "c",
"v" : 353
},
{
"k" : "e",
"v" : 113
}
]
}
db.test.drop();
db.test.insert({
"_id": 1,
"info": [{"k": "c", "v": 768}, {"k": "d", "v": 345}]
});
db.test.insert({
"_id": 2,
"info": [{"k": "e", "v": 333}]
});
db.test.insert({
"_id": 3,
"info": [{"k": "c", "v": 353}, {"k": "e", "v": 113}]
});
db.test.find().forEach(printjson);
var res = db.test.aggregate([
{$sort: {
"_id": 1
}},
{$unwind: "$info"},
{$group: {
"_id": "$info.k",
"v": {$last: "$info.v"}
}}
]);
printjson(res);
{
"result" : [
{
"_id" : "e",
"v" : 113
},
{
"_id" : "d",
"v" : 345
},
{
"_id" : "c",
"v" : 353
}
],
"ok" : 1
}
There are 2 ways:
1) use the Aggregation Framework to build a query
2) a knight’s move: when data arrives immediately into another collection, immediately write / update your “last values \u200b\u200bfor a specific key”, preserving the record id of the original collection in which this key value is stored . In this case, to select, you just need to make a simple request to this additional collection. This solution will be especially good if you have few keys, and just as good as turning around this large initial storage collection to get the last values of several dozen keys will look stupid ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question