如何查找和更新文档数组中的对象

How do you fin and update objects in a document's array

我已经绝望了几天,因为我正在寻找一种方法来更新数组中的对象 这是我的代码的一小段摘录

{
  "_id": {
    "$oid": "62684e70e89eca781cc4f384"
  },
  "user": "ronen",
  "roles": {
    "User": 2001,
    "Editor": 1984,
    "Admin": 5150
  },
  "password": "b$pO52RJD0zgFHDW6BBCo5iu3A5Lx0TCbCbzgjvc3FxxQZGUjblSPaK",
  "Stock": [
    {
      "sku": "777",
      "productname": "rone4n",
      "sendout": 5,
      "recived": 3,
      "totalinstock": 55,
      "location": "A770770",
      "_id": {
        "$oid": "626a9bb384cd350c6e784794"
      }
    },
    {
      "sku": "ex77xee",
      "productname": "ron",
      "sendout": 43,
      "recived": 34,
      "totalinstock": 444,
      "location": "fff",
      "_id": {
        "$oid": "626adab728fcc6005453a481"
      }
    }
  ],
 
}

我想 return 唯一 where "sku": "ex77xee" 不知道如何在数组中搜索对象

{
      "sku": "ex77xee",
      "productname": "ron",
      "sendout": 43,
      "recived": 34,
      "totalinstock": 444,
      "location": "fff",
      "_id": {
        "$oid": "626adab728fcc6005453a481"
      }

我更喜欢在 MongoDB 方面这样做, 我尝试使用 findONe 但我没有成功

您可以 运行 这个查询,您可以阅读更多关于 $elemMatch here

db.collection.find({
  stock: {
    $elemMatch: {
      sku: "ex77xee"
    }
  }
},
{
  "stock.$": 1,
  "user": 1, //<-- You can remove this, if you don't want these values
  "roles": 1, //<-- You can remove this, if you don't want these values
  "password": 1 //<-- You can remove this, if you don't want these values
})

你可以查看mongo playground here

$elemMatch 非常通用,如果需要,您可以稍后添加更多条件进行过滤