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 thearraythat matches your query condition (array.k": "v1"). - By using
array.$.rejected, you're explicitly telling MongoDB to update therejectedfield of that specific matching array element, rather than creating or modifying a top-level field.
Additional notes:
- If multiple elements in the
arraymatch thearray.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 anarrayFiltersparameter 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
相关产品推荐
相关产品推荐

