You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 yourCollectionName with the name of your MongoDB collection (e.g., auctions).
  • Customize the new bid's fields (Bidder details, Time, Amount) to match your actual data.
  • The $push operator will automatically append the new bid to the end of the Bid array. If the Bids object or Bid array 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:10:40