更新 BSON 文档的对象

Update an object of a BSON document

我正在尝试使用猫鼬更新我的 BSON 文档中的对象。 我想将状态从 0 更新为 1,其中 tagID 是 kLawOURVpz1IIjoQ2fhCvy7NM,tagUnit 是 8,tagNo 是 2

我试过:

db.updateOne(
 { "fileID": "0pdn3jdndndj3msms", "items.tagID": "kLawOURVpz1IIjoQ2fhCvy7NM", "items.tagUnit": 8, "items.tagNo": 2 },
 {
   $set: {
    "items.$.status": 1,
   }
 },
 { safe: true, upsert: true }
);

但是它更新了一个错误的对象。

我该怎么做,我的 BSON 文档是:

{
  "_id": "ID_GOES_HERE",
  "fileID": "0pdn3jdndndj3msms",
  "fileName": "Item List",
   "items": [
{
  "tagNo": 2,
  "status": 0,
  "tagID": "kLawOURVpz1IIjoQ2fhCvy7NM",
  "tagUnit": 5
},
{
  "tagNo": 2,
  "status": 0,
  "tagID": "kLawOURVpz1IIjoQ2fhCvy7NM",
  "tagUnit": 8
},
{
  "tagNo": 2,
  "status": 0,
  "tagID": "pOawOURVpz1IIjoQ2fhCvy7w3",
  "tagUnit": 81
},
{
  "tagNo": 4,
  "status": 0,
  "tagID": "kLawOURVpz1IIjoQ2fhCvy7NM",
  "tagUnit": 904
},
{
  "tagNo": 3,
  "status": 0,
  "tagID": "pOawOURVpz1IIjoQ2fhCvy7w3",
  "tagUnit": 24
},
{
  "tagNo": 2,
  "status": 0,
  "tagID": "pOawOURVpz1IIjoQ2fhCvy7w3",
  "tagUnit": 35
},
{
  "tagNo": 1,
  "status": 0,
  "tagID": "kLawOURVpz1IIjoQ2fhCvy7NM",
  "tagUnit": 11
},
{
  "tagNo": 2,
  "status": 0,
  "tagID": "kLawOURVpz1IIjoQ2fhCvy7NM",
  "tagUnit": 30
   }
 ]
 }

我将查询从;

db.updateOne(
 { "fileID": "0pdn3jdndndj3msms", "items.tagID": "kLawOURVpz1IIjoQ2fhCvy7NM", "items.tagUnit": 8, "items.tagNo": 2 },
 {
   $set: {
    "items.$.status": 1,
   }
 },
 { safe: true, upsert: true }
);

db.updateOne(
 { "fileID": "0pdn3jdndndj3msms",
   items: {
      $elemMatch: {
          tagID: "kLawOURVpz1IIjoQ2fhCvy7NM",
          tagUnit: 8,
          tagNo: 2,
      },
   }
 },
 {
   $set: {
    "items.$.status": 1,
   }
 },
 { safe: true, upsert: true }
);

这适用于第一个查询,因为有多个条件,$elemMatch 用于在一个元素中匹配 2 个或更多条件。如果没有$elemMatch,不同的条件可能会匹配到数组中的不同元素。