0

In my 'assemblies' collection, each document contains an embedded array of objects called 'partlist':

{
 "_id" : ObjectId("0001"),
 "pn" : "01",
 "title" : "MyAssembly",
 "partlist" : [ 
 {
    "id" : "",
    "pn" : "1234",
    "desc" : "myPart1",
 }, 
 {
    "id" : "",
    "pn" : "5678",
    "desc" : "myPart2",
 }]
}

Within each object, I need to copy the value from 'partlist.pn' into 'partlist.id'. I used:

db.assemblies.aggregate([{$set:{"partlist.id":"$partlist.pn"}}])

hoping to achieve this:

{
 "_id" : ObjectId("0001"),
 "pn" : "01",
 "title" : "MyAssembly",
 "partlist" : [ 
 {
    "id" : "1234",
    "pn" : "1234",
    "desc" : "myPart1",
 }, 
 {
    "id" : "5678",
    "pn" : "5678",
    "desc" : "myPart2",
 }]
}

Instead it returned to 'id' an array of ALL the 'pn' values in 'partlist':

{
 "_id" : ObjectId("0001"),
 "pn" : "01",
 "title" : "MyAssembly",
 "partlist" : [ 
 {
    "id" : [ 
        "1234",
        "5678"
     ],
    "pn" : "1234",
    "desc" : "myPart1",
 }, 
 {
    "id" : [ 
        "1234",
        "5678"
     ],
    "pn" : "5678",
    "desc" : "myPart2",
 }]
}

What is the correct syntax for copying the one value within each object?

1
  • It id, pn and desc all you have as fields, or are there more fields? Commented Nov 23, 2020 at 7:23

2 Answers 2

1

What you can do is, you can use $map to modify each elements and mearg the id with the help of $mergeObject

db.collection.aggregate([
  {
    $addFields: {
      "partlist": {
        $map: {
          input: "$partlist",
          in: {
            "$mergeObjects": [
              "$$this",
              {
                id: "$$this.pn"
              }
            ]
          }
        }
      }
    }
  }
])

Working Mongo playground

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

3 Comments

Thanks varman, that did the trick. So much to learn and so little time...
@user1925590 consider to accept the answer which may help others in future
Sure. How do I do that?
0
  • If the pn does not exist it retrieves initial object.
db.collection.aggregate([
  {
    $addFields: {
      partlist: {
        $map: {
          input: "$partlist",
          as: "p",
          in: {
            $cond: [
              "$$p.pn",
              {
                $mergeObjects: [
                  "$$p",
                  {
                    "id": "$$p.pn"
                  }
                ]
              },
              "$$p"
            ]
          }
        }
      }
    }
  }
])

Playground

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.