0

I have such document

{
    "_id" : "N4H7gYQwNXwTiEe62",
    "createdAt" : ISODate("2020-05-07T20:18:59.144Z"),
    "title" : "Two roads",
    "userId" : "CnugxoBWs4ox6vG2k",
    "awards" : [ 
        {
            "type" : "suggested",
            "place" : 1.0,
            "addedAt" : ISODate("2020-10-23T20:33:58.885Z")
        },
        {
            "type" : "voted",
            "place" : 3,
            "addedAt" : ISODate("2020-10-23T20:33:58.885Z")
        }
    ]
}

Is it possible to write a query which add a new element in "awards" if "type" is not exists (fexample: new type "removed"), or update if type exists already as "suggested" or "voted". I need to update "place" and "addedAt".

1 Answer 1

1

Query to add a new element in "awards" if particular "type" does not exist (fexample: new type "removed"):

db.collection.update({
  "awards.type": {
    "$ne": "removed"
  }
},
{
  "$addToSet": {
    "awards": {
      type: "removed"
    }
  }
},
{
  multi: true
})

MongoDB Playground

Query to update if type exists already as "suggested":

db.collection.update({
  "awards.type": "suggested"
},
{
  "$set": {
    "awards.$.place": 0 /* replace 0 with your value */
  }
},
{
  multi: true
})

MongoDB Playground

If you want to update multiple documents, make sure you add multi:true

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.