jtyjty99999
jtyjty99999

Reputation: 251

how to append data to an existing key's value in mongodb

For example my data is {'abc':'def'},that has a single key-value;

I want this:

do something...//data has been changed to {'abc':'defghi'} or {'abc':'['def','ghi']'}

And I have used this code in nodejs:

                var tmp2 = {'userid:location:2013-01-02 15':['092030', '12122.11260E']};

            collection.insert(tmp2, {safe:true}, function (err, result) {
                var i = 0;
                var a = +new Date();
                while(i<300000){
                    tmp2['userid:location:2013-01-02 15'].push(i);
        collection.save(tmp2, function () { })      
                    i+=1;
                }
                var b = +new Date();
                console.log(b-a)
            });

the save api can replace the same key's value,so use push,I can append data to an exising key's value;

But there are some problems:

  1. The push operation was badly performanced.Single save can run 15000/s,but when use push,it's 1500/s.
  2. If I have two clients,both want to append data,the later one will cover the earlier one's data,not append. How can I solve this problem?Is there an API?

Upvotes: 4

Views: 6302

Answers (1)

Sim
Sim

Reputation: 13528

The problem is that you are using save which overrides the document: last one wins. You should consider using atomic updates with $push, perhaps via findAndModify.

Upvotes: 5

Related Questions