A
A
akamoroz2013-03-11 09:06:06
JavaScript
akamoroz, 2013-03-11 09:06:06

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  ] 
}

You need to make a selection by all the latest values ​​in the info array, sorted by _id (horror ...), in short, it should turn out:
[ 'c':353,  'e':113, 'd':345  ] 


Good people, in which direction to dig?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vyacheslav Slinko, 2013-03-11
@KeepYourMind

In general, with this structure:

{
  "_id" : 3,
  "info" : [
    {
      "k" : "c",
      "v" : 353
    },
    {
      "k" : "e",
      "v" : 113
    }
  ]
}

Here is the solution:
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);

Here is the result of running aggregation:
{
  "result" : [
    {
      "_id" : "e",
      "v" : 113
    },
    {
      "_id" : "d",
      "v" : 345
    },
    {
      "_id" : "c",
      "v" : 353
    }
  ],
  "ok" : 1
}

A
Anton Kuzmichev, 2013-03-11
@Assargin

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 ...

V
Vyacheslav Slinko, 2013-03-11
@KeepYourMind

What does the last value mean?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question