Amirhossein Azhdari
Amirhossein Azhdari

Reputation: 189

Change value of a field in embed document with condition in mongo DB

I try to get a data from the database. But I've had a problem in a section where I can't edit the value of the embedded fields. I want to put the boolean value instead of the mobile number. if it has a value, equal to the true and if it does not have a value, it will be false.

I have document like this in my collection:

{
    "_id": ObjectId("606d6ea237c2544324925c61"),
    "title": "newwww",
    "message": [{
        "_id": ObjectId("606d6e1037c2544324925c5f"),
        "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "user_id": null,
        "user_full_name": null,
        "user_mobile_number": null,
        "submit_date": {
            "$date": "2021-04-07T08:32:16.093Z"
        }
    }, {
        "_id": ObjectId("606d6edc546feebf508d75f9"),
        "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "user_id": null,
        "user_full_name": null,
        "user_mobile_number": "9653256482",
        "submit_date": {
            "$date": "2021-04-07T08:35:40.881Z"
        }
    }],
    "user_mobile_number": "9652351489",
}

Do query:

db.ticket.aggregate([{"$match": {"_id": ObjectId("606d6ea237c2544324925c61")}}, {
        "$project": {"message.is_admin":{
                "$let": {
                    vars: {
                        mobile_number: "$message.user_mobile_numebr"
                    },
                    in: {
                        "$cond": [{$eq: ['$$mobile_number', null]},false,true ]
                    }
                }
            }
        }
    }])

and result is:

[
  {
    "_id": ObjectId("606d6ea237c2544324925c61"),
    "message": [
      {
        "is_admin": true
      },
      {
        "is_admin": true
      }
    ]
  }
]

but i want result like this:

[
  {
    "_id": ObjectId("606d6ea237c2544324925c61"),
    "message": [
      {
        "is_admin": false
      },
      {
        "is_admin": true
      }
    ]
  }
]

means I want when message.user_mobile_number has value, get true and when value is null get false.


How can I do this?

Upvotes: 2

Views: 662

Answers (1)

Demo - https://mongoplayground.net/p/h_zkRfDbZrS

Use $map

db.collection.aggregate([
  {
    "$project": {
      "message": {
        "$map": {
            input: "$message",
            "as": "message",
            "in": { 
                "$cond": [{ "$eq": [ "$$message.user_mobile_number", null ] }, { is_admin: false }, { is_admin: true } ]
            }
        }
      }
    }
  }
])

Upvotes: 2

Related Questions