共用方式為


findAndModify

findAndModify 指令用於原子性修改並回傳單一文件。 此指令適用於需要單步讀取與更新文件的操作,以確保資料一致性。 常見的使用情境包括實作計數器、佇列及其他原子操作。

語法

指令 findAndModify 的語法如下:

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

參數

  • 查詢:文件可修改的選擇標準。
  • sort:若查詢選擇多個文件,決定要修改哪份文件。
  • 移除:若 true,則移除所選文件。
  • 更新:修改內容將適用。
  • 新:true,則回傳修改後的文件而非原始文件。
  • 欄位:限制欄位回傳至匹配文件。
  • UPSERT:如果 true,若沒有與查詢相符的文件,則建立新文件。

範例

範例一:更新總銷售額

假設我們想將商店的總銷售額更新為「 _id e5767a9f-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'
  ]
}

範例二:新增促銷活動

我們來新增一個名為「電子超級省錢」的促銷活動,使用 _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'
  ]
}

範例三:移除促銷活動

假設我們想從商店移除帶有 _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'
  ]
}