MongoDB技术问询:如何向嵌套数组插入对象以更新文档
Add a New Bid to the
Bids.Bid Array in MongoDB Got it, let's walk through how to insert a new bid entry into the Bid array nested under the Bids property of your MongoDB document.
Using updateOne for Single Document Update
Since you're targeting a specific document by its _id, the updateOne method is the right choice here. We'll use the $push operator—this is MongoDB's go-to for adding elements to an array without overwriting existing data.
Here's a complete example you can adapt for your collection:
// Replace "yourCollectionName" with your actual collection name db.yourCollectionName.updateOne( // Query: Find the document with the target _id { "_id": "1044300051" }, // Update: Push the new bid into the Bids.Bid array { $push: { "Bids.Bid": { "Bidder": { "_id": "new_bidder_123", "_Rating": 400, "Location": "Portland, OR", "Country": "USA" }, "Time": "Dec-11-01 09:15:30", "Amount": 1.75 } } } )
Key Details to Note:
- Replace
yourCollectionNamewith the name of your MongoDB collection (e.g.,auctions). - Customize the new bid's fields (
Bidderdetails,Time,Amount) to match your actual data. - The
$pushoperator will automatically append the new bid to the end of theBidarray. If theBidsobject orBidarray didn't exist in the document, MongoDB would create them for you—handy if you're dealing with documents that might not have the nested structure yet.
Adding Multiple Bids at Once
If you need to insert more than one bid in a single operation, use $push with the $each modifier:
db.yourCollectionName.updateOne( { "_id": "1044300051" }, { $push: { "Bids.Bid": { $each: [ { "Bidder": { "_id": "bidder_a", "_Rating": 280, "Location": "Seattle", "Country": "USA" }, "Time": "Dec-12-01 14:20:00", "Amount": 1.80 }, { "Bidder": { "_id": "bidder_b", "_Rating": 190, "Location": "Vancouver", "Country": "Canada" }, "Time": "Dec-12-01 14:25:00", "Amount": 1.90 } ] } } } )
This will add both bids to the Bid array in one go.
内容的提问来源于stack exchange,提问作者Roc47HS
相关产品推荐
相关产品推荐

