Home > Software design >  MongoDB v3.4 initialize new field value based on array's value of each record
MongoDB v3.4 initialize new field value based on array's value of each record

Time:01-21

I have a collection with the following structure:

{
    "_id":NUUID(...),
    "MyArray": [{
        "Name": "...",
        "MyId": "..."
    },
    {...}]
},
{...}

My task is to introduce a new field ArrayId which has to contain value from MyId if MyArray.Name is X and contain nothing (empty string) otherwise.

I tried the following:

db.getCollection('myCollection').aggregate([
    {$addFields: {"ArrayId": {$cond: {if: {$eq: ["$MyArray.Name", "X"]}, then: "$MyArray.MyId", else: ""}}}},
    {$out: "myCollection_backup"}
])

but the resulting collection has empty ArrayId for all records.

Can you please help find the error? Is there an easier way to do this in mongo 3.4?

CodePudding user response:

Maybe something like this:

db.collection.aggregate([
{
 $addFields: {
  "ArrayId": {
    "$reduce": {
      "input": "$MyArray",
      "initialValue": "",
      "in": {
        $concat: [
          "$$value",
          {
            "$cond": {
              if: {
                $eq: [
                  "$$this.Name",
                  "X"
                ]
              },
              then: "$$this.MyId",
              else: ""
            }
          }
        ]
      }
    }
  }
}
}
])

Explained:

Use $addFileds/$reduce to $concat the MyArray.MyId into the new variable SArrayId in case MyArray.Name="X"

( This is in case we expect only one of MyArray.Name=X , what is expected to happen in case there is more then 1x MyArray.Name=X ? )

Playground

Here is version updating only when it finds first Name=X(in case there is more then one Name=X):

Playground2

  • Related