MongoDB Collection Update: Initialize a Document with Default Values

I am trying to figure out time series using MongoDB. A common decision made by the community is to use subdocuments to store information at different levels of detail (see Schema schema for time series data in MongoDB ).

For example, look at the following document:

{
  timestamp_minute: ISODate("2013-10-10T23:06:00.000Z"),
  type: "memory_used",
  values: [
    999999,   // 1 second
    …
    1000000,  // nth second
    1500000,  // n+1th second
    … 
    2000000   // 60th
  ]
}

The document is indexed by minute information and contains a subdocument that stores more detailed information for every second.

So far so good. This approach requires optimization for proper operation:

Another optimization [..] pre-distributes all documents for the upcoming period of time; This never causes an existing document to grow or move to disk.

, $setOnInsert update.

db.getCollection('aCollection').update(
    {
      timestamp_minute: ISODate("2013-10-10T23:06:00.000Z"),
      type: "memory_used"
    },
    {
      $setOnInsert: { values: {'0': 0, '1': 0, '2': 0}},
      $inc: {"values.30": 1}
    },
    { upsert: true }
)

, . istruction :

Cannot update 'values' and 'values.30' at the same time

.

: - ? , , , ( type.

.

+4
1

. ​​.

, MongoDB . , :

  • , . , . , . , .
  • , , , , . . ( ) . insert . , : , - .
  • .

.

// Firt of all, try the update
var result = db.test.update(
  {timestamp_minute: ISODate("2013-10-10T23:06:00.000Z"), type: "memory_used"},
  {$inc: {"values.39": 1}},
  {upsert: false}
);
// If the update do not succeed, then try to insert the document
if (result.nModified === 0) {
  try {
    db.test.insert(/* Put here the whole document */);
  } catch (err) {
    console.log(err);
  }
  // Here we are sure that the document exists.
  // Retry to execute the update statement
  db.test.update(/* Same update as above */);
}

, : _id . _id '2013-10-10T23:06:00.000Z-memory_used. , 2. .

+4

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


All Articles