Conditionally updating document based on date field

I’m currently attempting to use an aggregation pipeline to conditionally update a document based on a date field (the date field is provided by an API, not controlled by Mongo).

I’m using the $replaceWith stage, as I’d like to update the entire document if the condition is met. The issue I am having is in the else branch of $cond. I’d like no update to happen if $cond does not return true, but with my query below I am getting an error.

db.getCollection("port_status").updateOne({
        id: 'abc123'
    }, 
    [
        {
            $replaceWith: {
                $cond: {
                    if: { $lt: ['$updatedAt', ISODate("2022-01-10T19:56:00.025+0000")] },
                    then: { 
                      id: 'abc123',
                      locId: 'aaa',
                      updatedAt: '2022-05-02T01:00:00.000Z'
                    },
                    else: null
                }
            }

        }
    ]
)

Simply put your updatedAt condition inside your query argument.

If condition is true document will found and updated.

If condition is false no document will be found and not update will occur.

I’m not sure I’m totally following, do you mean something like this?

db.getCollection("port_status").updateOne({
        id: 'abc123',
        updatedAt: {
            $cond: {
                if: { $lt: ['$updatedAt', ISODate("2022-01-10T19:56:00.025+0000")] },
          }
        }

    }, 
    {
        $set: {
            id: 'abc123',
            locId: 'aaa',
            updatedAt: '2022-05-02T01:00:00.000Z'
        }

    }
)

I’m getting an error: unknown operator: $cond

Yes but you have to follow the correct syntax.

See https://www.mongodb.com/docs/manual/reference/operator/query/lt/ and follows the examples.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.