Home > Mobile >  MongoDB: how to pass current value to operator?
MongoDB: how to pass current value to operator?

Time:02-10

Here is sample db structure where I'm trying to modify value of every work_starts_at.

{
    "_id": 1,
    "work_week": [
        {'name': 'ponedeljak', 'work_hours': []},
        {'name': 'utorak', 'work_hours': []},
    ]
},
{
    "_id": 2,
    "work_week": [
        {'name': 'monday', 'work_hours': [
            {'work_starts_at': 1, 'work_ends_at': 2}
        ]},
    ]
},
{
    "_id": 3,
    "work_week": [
        {'name': 'понедельник', 'work_hours': [
            {'work_starts_at': 2, 'work_ends_at': 3},
            {'work_starts_at': 6, 'work_ends_at': 7},
        ]},
        {'name': 'вторник', 'work_hours': []},
    ]
}

The best solution I came to is the following (in python), but instead of subtracting 5 from current value of work_week.work_hours.work_starts_at it's traversing I got null. I suppose it's because construction $$CURRENT.work_hours.work_starts_at doesn't point to work_starts_at, so I'm actually subtracting 5 from null.

How can I properly address value of currently traversed element?

collection.update_many(
{},
[
    {
        '$set': {
            'work_week.work_hours.work_starts_at': {
                '$subtract': ['$$CURRENT.work_hours.work_starts_at', 5]
            }
        }
    }
]

CodePudding user response:

You can do this way from the mongo shell (it must be very similar in python):

db.collection.update({
 "work_week.work_hours.work_starts_at": {
  $exists: true
}
},
{
 $inc: {
   "work_week.$[].work_hours.$[].work_starts_at": -5
}
},
{
 multi: true
})

playground

CodePudding user response:

Thanks to @R2D2! I've translated it to Python (pymongo):

collection.update_many(
        {'work_week.work_hours.work_starts_at': {'$exists': True}},
        {'$inc': {
            'work_week.$[].work_hours.$[].work_starts_at': -5
        }}
    )
  • Related