Home > Blockchain >  Update an object of a BSON document
Update an object of a BSON document

Time:06-02

I am trying to update an object in my BSON document using mongoose. I want to update the status from 0 to 1 where tagID is kLawOURVpz1IIjoQ2fhCvy7NM, tagUnit is 8 and tagNo is 2

I have tried:

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

but it updates a wrong object.

How can I go about that, my BSON document is:

{
  "_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
   }
 ]
 }

CodePudding user response:

I changed the query from;

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

to

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

This worked over the first query because there is more than 1 condition and $elemMatch is for matching 2 or more conditions in one element. Without $elemMatch, different conditions may match different element in the array.

  • Related