简体   繁体   中英

Insert embedded document into an existing document in MongoDB

I have a document with a structure like this:

Product (root)
   Document1 (embedded)
   Document2
   ...
   DocumentN
      Part1  (embedded)
      Part2
      ...
      PartN

I have POCOs mapped to the structure. At one point, user creates a Product, which is the saved to the database immeadetly. The user then creates a document, after which the Product entity is saved again to the database (as I understand, it should do an update as the product entity already exists in db). However, when I create a N-th document inside a product and try to save it, I get an error that I'm trying to upload too much (maximum upload size limit is 16MB).

How can I update the Product document so that I would insert (upload) only the new Document into the Product instead of uploading the whole product to the database again ?

Thanks!

You need to use upserts. You do this via an update and specifying that it should be an upsert. This will allow you to set/update specific properties without specifying the entire object.

Assuming your products have a productId field which you'll use to identify which product to update:

db.products.update( { "productId":1234 }, { $set: { document1: { part1: "foo" } } }, true );

The last param (true) indicates that this is an upsert. Your driver may have a slightly different way of indicating the upsert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM