findAndModify

适用对象: MongoDB vCore

findAndModify 命令用于以原子方式修改和返回单个文档。 此命令对于需要通过一个步骤读取和更新文档的操作很有用,可确保数据一致性。 常见用例包括实现计数器、队列和其他原子操作。

语法

findAndModify 命令的语法如下:

db.collection.findAndModify({
   query: <document>,
   sort: <document>,
   remove: <boolean>,
   update: <document>,
   new: <boolean>,
   fields: <document>,
   upsert: <boolean>
})

参数

  • query:要修改的文档的选择条件。
  • sort:如果查询选择多个文档,则确定要修改哪个文档。
  • remove:如果为 true,则删除所选文档。
  • update:要应用的修改。
  • new:如果为 true,则返回修改后的文档,而不是原始文档。
  • fields:限制要对匹配文档返回的字段。
  • upsert:如果为 true,则当没有文档与查询匹配时,创建一个新文档。

示例

示例 1:更新总销售额

假设我们要将 _id 为“e5767a9f-cd95-439c-9ec4-7ddc13d22926”的商店的总销售额更新为 550000.00 并返回更新后的文档。

db.stores.findAndModify({
   query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" },
   update: { $set: { "sales.totalSales": 550000.00 } },
   new: true
})

示例输出

[mongos] StoreData> db.stores.findAndModify({
...    query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" },
...    update: { $set: { "sales.totalSales": 550000.00 } },
...    new: true
... })
{
  _id: 'e5767a9f-cd95-439c-9ec4-7ddc13d22926',
  name: "Marina's Eyewear Bargains",
  location: { lat: -87.4376, lon: 42.2928 },
  staff: { totalStaff: { fullTime: 20, partTime: 6 } },
  sales: {
    totalSales: 550000,
    salesByCategory: [
      { categoryName: 'Round Sunglasses', totalSales: 39621 },
      { categoryName: 'Reading Glasses', totalSales: 1146 },
      { categoryName: 'Aviators', totalSales: 9385 }
    ]
  },
  promotionEvents: [
    {
      eventName: 'Incredible Discount Days',
      promotionalDates: {
        startDate: { Year: 2024, Month: 2, Day: 11 },
        endDate: { Year: 2024, Month: 2, Day: 18 }
      },
      discounts: [
        { categoryName: 'Square Sunglasses', discountPercentage: 16 },
        { categoryName: 'Safety Glasses', discountPercentage: 17 },
        { categoryName: 'Wayfarers', discountPercentage: 7 },
        { categoryName: 'Eyewear Accessories', discountPercentage: 12 }
      ]
    }
],
  tag: [
    '#ShopLocal',
    '#FashionStore',
    '#SeasonalSale',
    '#FreeShipping',
    '#MembershipDeals'
  ]
}

示例 2:添加新的促销活动

让我们向 _id_ 为“e5767a9f-cd95-439c-9ec4-7ddc13d22926”的商店添加一个名为“电子产品超值优惠”的新促销活动,并返回更新后的文档。

db.stores.findAndModify({
   query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" },
   update: { $push: { "promotionEvents": {
       "eventName": "Electronics Super Saver",
       "promotionalDates": {
         "startDate": "2025-09-31",
         "endDate": "2025-09-31"
       },
       "discounts": [
         {
           "categoryName": "Laptops",
           "discountPercentage": 45
         },
         {
           "categoryName": "Smartphones",
           "discountPercentage": 25
         }
       ]
   }}},
   new: true
})

示例输出

[mongos] StoreData> db.stores.findAndModify({
...    query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" },
...    update: { $push: { "promotionEvents": {
...        "eventName": "Electronics Super Saver",
...        "promotionalDates": {
...          "startDate": "2025-09-31",
...          "endDate": "2025-09-31"
...        },
...        "discounts": [
...          {
...            "categoryName": "Laptops",
...            "discountPercentage": 45
...          },
...          {
...            "categoryName": "Smartphones",
...            "discountPercentage": 25
...          }
...        ]
...    }}},
...    new: true
... })

{
  _id: 'e5767a9f-cd95-439c-9ec4-7ddc13d22926',
  name: "Marina's Eyewear Bargains",
  location: { lat: -87.4376, lon: 42.2928 },
  staff: { totalStaff: { fullTime: 20, partTime: 6 } },
  sales: {
    totalSales: 550000,
    salesByCategory: [
      { categoryName: 'Round Sunglasses', totalSales: 39621 },
      { categoryName: 'Reading Glasses', totalSales: 1146 },
      { categoryName: 'Aviators', totalSales: 9385 }
    ]
  },
  promotionEvents: [
    {
      eventName: 'Electronics Super Saver',
      promotionalDates: { startDate: '2025-09-31', endDate: '2025-09-31' },
      discounts: [
        { categoryName: 'Laptops', discountPercentage: 45 },
        { categoryName: 'Smartphones', discountPercentage: 25 }
      ]
    }
  ],
  tag: [
    '#ShopLocal',
    '#FashionStore',
    '#SeasonalSale',
    '#FreeShipping',
    '#MembershipDeals'
  ]
}

示例 3:删除促销活动

假设我们要从 _id 为“e5767a9f-cd95-439c-9ec4-7ddc13d22926”的商店中删除“电子产品超值优惠”促销活动并返回原始文档。

db.stores.findAndModify({
   query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" },
   update: { $pull: { "promotionEvents": { "eventName": "Electronics Super Saver" } } },
   new: true
})

示例输出

[mongos] StoreData> db.stores.findAndModify({
...    query: { "_id_": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" },
...    update: { $pull: { "promotionEvents": { "eventName": "Electronics Super Saver" } } },
...    new: true
... })
null
[mongos] StoreData> db.stores.findAndModify({
...    query: { "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" },
...    update: { $pull: { "promotionEvents": { "eventName": "Electronics Super Saver" } } },
...    new: true
... })
{
  _id: 'e5767a9f-cd95-439c-9ec4-7ddc13d22926',
  name: "Marina's Eyewear Bargains",
  location: { lat: -87.4376, lon: 42.2928 },
  staff: { totalStaff: { fullTime: 20, partTime: 6 } },
  sales: {
    totalSales: 550000,
    salesByCategory: [
      { categoryName: 'Round Sunglasses', totalSales: 39621 },
      { categoryName: 'Reading Glasses', totalSales: 1146 },
      { categoryName: 'Aviators', totalSales: 9385 }
    ]
  },
  promotionEvents: [
    {
      eventName: 'Incredible Discount Days',
      promotionalDates: {
        startDate: { Year: 2024, Month: 2, Day: 11 },
        endDate: { Year: 2024, Month: 2, Day: 18 }
      },
      discounts: [
        { categoryName: 'Square Sunglasses', discountPercentage: 16 },
        { categoryName: 'Safety Glasses', discountPercentage: 17 },
        { categoryName: 'Wayfarers', discountPercentage: 7 },
        { categoryName: 'Eyewear Accessories', discountPercentage: 12 }
      ]
    }
  ],
  tag: [
    '#ShopLocal',
    '#FashionStore',
    '#SeasonalSale',
    '#FreeShipping',
    '#MembershipDeals'
  ]
}