I have the following table:
I have to set offerCategoryState
column with following rule:
- DEPOSIT or INSURANCE -> ENABLED
- DIGITAL_CARD -> SOON
- others -> BLOCKED
I wrote query for doing this with updateMany()
:
db.OFFER_CATEGORIES.updateMany(
{},
{ $set: { offerCategoryState: { $switch: {
branches: [
{ case: { $eq: [ "$type", 'DEPOSIT' ] }, then: "ENABLED" },
{ case: { $eq: [ "$type", 'INSURANCE' ] }, then: "ENABLED" },
{ case: { $eq: [ "$type", 'DIGITAL_CARD' ] }, then: "SOON" },
],
default: "BLOCKED"
} } } }
);
Unfortunatelly, it fails:
Write error: WriteError{code=52, message='The dollar ($) prefixed field '$switch' in 'offerCategoryState.$switch' is not valid for storage.', details={}
How to write such a mongo DB query where setting one column depends on another?
Or even more how to add this new columnt if it doesn't exists at current schema (when set up at new environment).
CodePudding user response:
$switch
is used in .aggregation
only so can't use it in .updateMany
.
Alternatively you can do this
db.OFFER_CATEGORIES.updateMany({}, { $set: { offerCategoryState: 'BLOCKED' } })
db.OFFER_CATEGORIES.updateMany({ type: 'DEPOSIT' }, { $set: { offerCategoryState: 'ENABLED' } })
db.OFFER_CATEGORIES.updateMany({ type: 'INSURANCE' }, { $set: { offerCategoryState: 'ENABLED' } })
db.OFFER_CATEGORIES.updateMany({ type: 'DIGITAL_CARD' }, { $set: { offerCategoryState: 'SOON' } })