次の方法で共有


findAndModify

findAndModify コマンドは、1 つのドキュメントをアトミックに変更して返すために使用されます。 このコマンドは、1 つの手順でドキュメントの読み取りと更新を必要とする操作で、データの一貫性を確保するのに役立ちます。 一般的なユース ケースには、カウンター、キュー、およびその他のアトミック操作の実装が含まれます。

構文

findAndModify コマンドの構文は次のとおりです。

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

パラメーター

  • クエリ: 変更するドキュメントの選択条件。
  • sort: クエリが複数のドキュメントを選択した場合に変更するドキュメントを決定します。
  • remove: true場合は、選択したドキュメントを削除します。
  • update: 適用する変更。
  • new: true場合は、元のドキュメントではなく変更されたドキュメントを返します。
  • fields: 一致するドキュメントに対して返すフィールドを制限します。
  • upsert: true場合は、クエリに一致するドキュメントがない場合は、新しいドキュメントを作成します。

例示

例 1: 売上合計を更新する

"e5767a9f-cd95-439c-9ec4-7ddc13d22926" _id ストアの売上合計を 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: プロモーション イベントを削除する

"e5767a9f-cd95-439c-9ec4-7ddc13d22926" を _id 使用してストアから "Electronics Super Saver" プロモーション イベントを削除し、元のドキュメントを返したいとします。

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