How to use mongodb-insert-on-duplicate-key-update?

1.6k views Asked by At

I have a table with 3 columns: name, age, tm.

It has a compound index on (name, age)

If use MySQL, SQL may be like this:

insert into tt(name,age,tm) values('chenlong', 29, 1504437683) on duplicate key update tm = 1504437683

How to use in mongodb?

db.tt.find()

{ "_id" : ObjectId("59abe43ade8616599017a085"), "name" : "chenlong", "age" : 29, "tm" : ISODate("2017-09-03T11:32:04.156Z") }

    db.tt.update(
        {name:'chenlong',age:29},
        {
            $set: {tm:ISODate()},
            $setOnInsert: {tm:ISODate()}
        },
        { upsert: true }
    )

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

    db.tt.find()

{ "_id" : ObjectId("59abe43ade8616599017a085"), "name" : "chenlong", "age" : 29, "tm" : ISODate("2017-09-03T11:33:09.359Z") }

It's okay, column tm become newer, but add a new record, error happened.

db.tt.update(
    {name:'chenlong',age:30},
    {
        $set: {tm:ISODate()},
        $setOnInsert: {tm:ISODate()}
    },
    { upsert: true }
)

WriteResult({
        "nMatched" : 0,
        "nUpserted" : 0,
        "nModified" : 0,
        "writeError" : {
                "code" : 16836,
                "errmsg" : "**Cannot update 'tm' and 'tm' at the same time**"
        }
})

How to resolve the problem? Thanks.

1

There are 1 answers

0
Saif On

This will work

db.tt.update(
    {name:'chenlong',age:30},
    {
        $set: {tm:ISODate()}    
    },
    { upsert: true } 
)

If document matches it will update or upsert will occur.