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

MongoDB中$set操作未按预期生效的技术问询

Fixing Your MongoDB Array Element Update via mLab API

The problem with your current code is that your $set operation is targeting a top-level rejected field instead of the specific element inside the array that matches your query. MongoDB requires using the positional operator $ to update the correct array element that aligns with your search conditions.

Here's the corrected API call code:

var val1 = "val1";
var v1 = "v1";

request.put(
  'https://api.mlab.com/api/1/databases/DB/collections/doc?q={"key": "'+val1+'","array.k":"'+v1+'"}&apiKey=YOUR_API_KEY',
  { 
    json: { 
      "$set": { "array.$.rejected": "1" } 
    } 
  },
  function (error, response, body) {
    if (error) {
      console.error('Update failed:', error);
      return;
    }
    console.log('Update successful:', body);
  }
);

Why this works:

  • The positional operator $ acts as a placeholder for the first element in the array that matches your query condition (array.k": "v1").
  • By using array.$.rejected, you're explicitly telling MongoDB to update the rejected field of that specific matching array element, rather than creating or modifying a top-level field.

Additional notes:

  • If multiple elements in the array match the array.k": "v1" condition, the $ operator will only update the first matching element. To update all matching elements, you'd use the $[] filtered positional operator (requires MongoDB 3.6+), which would involve adding an arrayFilters parameter to your request.
  • Double-check that your API key is correctly included in the URL and that your mLab database/collection names are accurate.

Content of the question comes from Stack Exchange, question author tester9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:14:23