Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
986 views
in Technique[技术] by (71.8m points)

mongodb - create doc if not exist, else push to array

I have a document in the following form:

{
"_id" : ObjectId("4d2d8deff4e6c1d71fc29a07"),
"user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0",
"events" : [
        {
                "profile" : 10,
                "data" : "....."
        }
        {
                "profile" : 10,
                "data" : "....."
        }
        {
                "profile" : 20,
                "data" : "....."
        }
        ...
   ]
 }

I'd like to have some sort of upsert statement. It needs to add an event to the events array for user_id in case there is already such doc exist, else it needs to create the doc with the event item.

Can that be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do upserts in Mongo, see "Upserts with Modifiers" from the Mongo doc:

You may use upsert with a modifier operation. In such a case, the modifiers will be applied to the update criteria member and the resulting object will be inserted.

The query you need will look like:

db.events.update( { "user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0" }, 
{ $push : { "events" : { "profile" : 10, "data" : "X"}}}, {"upsert" : true});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...