How to atomically add a sequentially increasing identifier to a set of name / identifier pairs

I need to assign consecutively increasing nameset identifiers. It depends on the:

A field that contains the following identifier to be generated: curId

A set mysetcontaining a name / value pair, where value is an identifier and name is a name

Problem:

I need to atomize:
1. Make sure it mysetcontains a name. If not,
2. Generate a new identifier using $ inc.
3. Insert the name / id pair into myset.

I can’t find a way to do this in mongodb, at least without introducing race conditions. Suggestions are welcome.

Refresh

Example document (how it should look).

Before adding 'c':

{

    "mySet": [
        {
            "name": 'a',
            "value" : 1
        },
        {
            "name": 'b',
            "value" : 2
        }
    ]
}

'c'. 3, , 'c'.

{

    "mySet": [
        {
            "name": 'a',
            "value" : 1
        },
        {
            "name": 'b',
            "value" : 2
        },
        {
            "name": 'c',
            "value" : 3
        }
    ]
}

'c' . , "c" . "3", id "c".

+4
2

, , nextId, , . :

{ 
  "curId": 1,
  "mySet" : [  ]
}

, "" ( ), :

var Name = "a";
var curId = db.coll.findOne({"mySet.name":{"$ne":Name}},{"_id":0,"curId":1}).curId;

/* curId variable is now 1 */
var result = db.coll.update(
    { "mySet.name" : {"$ne":Name}, "curId":curId },
    { "$push": {"mySet" : {"name":Name,"value":curId} }, "$inc":{"curId":1} }
);

if (result.nModified == 0) {
   print("We lost - someone else must have gotten there first");
}

:

  • , Name mySet.

  • curId, , , .

  • curId $push , curId - curId, .

+1
db.counter.insert({"_id": "myCollectionName", "count": 1})

. , . http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/ . .

EDIT: , , 3 . $push (http://docs.mongodb.org/manual/reference/operator/update/push/). , ( 2 id 1), , , , . $push in conjuction findandmodify (http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/), .

0

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


All Articles