你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

findAndModify

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

Syntax

命令的 findAndModify 语法如下所示:

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

参数

  • 查询:要修改的文档的选择条件。
  • sort:确定查询选择多个文档时要修改的文档。
  • remove:如果 true,则删除所选文档。
  • 更新:要应用的修改。
  • new:如果 true返回修改后的文档,而不是原始文档。
  • 字段:限制为匹配文档返回的字段。
  • 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:添加新的促销事件

让我们使用“e5767a9f-cd95-439c-9ec4-7ddc13d22926”将名为“电子超级保存器”的新促销活动添加到商店 _id_ ,并返回更新的文档。

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'
  ]
}