2

I have a collection of documents, and there is one thing that is common for all documents - an ID field that is nested.

Document for example:

{
    "_id": <generated guid>
    "item": {
        "product": {
            "id": <guid>
            .. more fields
        }
    },
    "source": "Good Store"
}

I would like to set (at creation) the _id guid to be the guid that inside the product's scope. Is that possible?

I tried to search for it and didn't found an answer.

When I tried to map the object (using C#), I got an error that indicates that I can't map a nested field to the Id field.

theOtherOne
  • 21
  • 1
  • 4

1 Answers1

0

I see the following options:

1.

    db.coll.updateMany(
       { },
       [   
          { $addFields: { a : 10 } },   // just example, you need to get a data from some other document 
                                        // and then you can add him as "_id" with `upsert: true`. 
                                        // This _id should not present in the collection before
          { $set: { "_id": "$a" } },    // because it's upsert=true and such _id is not in the collection yet
                                        // the actually inserted _id will be value in `$a`
       ],
       { upsert: true }
    )
  1. Use diff collection and $out stage:

     MongoDB Enterprise mongos> db.coll.insertOne({ "_id": 1, "item": { "product": { "id": 11 } },   "source": "Good Store" }) // your current case
     { "acknowledged" : true, "insertedId" : 1 }
     MongoDB Enterprise mongos> db.coll.aggregate( [ { $set: { _id : "$item.product.id" }}, { $out: "coll2" } ]) // inserting _id you want for the coll2
     MongoDB Enterprise mongos> db.coll2.find() // check that _id is changed
     { "_id" : 11, "item" : { "product" : { "id" : 11 } }, "source" : "Good Store" }
    

you can also make aggregation output into current collection, but pay attention that $out actually removes all content in your collection and replaces it by aggregate result

  1. also you can use approach from here where you save a new document with updated _id and remove the old one
dododo
  • 3,872
  • 1
  • 14
  • 37
  • About 1 - Is it possible to update the _id field? I can't do that with c# driver and even with the shell on google the answer is no. – theOtherOne Jun 08 '22 at 07:44
  • no, as I wrote above this value is immutable. In #1, the key point that `upsert=true` and this is a new document for collection. In this case when `upsert=true`, effectively happened operation is `insert`, not `update` – dododo Jun 08 '22 at 11:39