nightroman / Mdbc

MongoDB Cmdlets for PowerShell
Apache License 2.0
141 stars 16 forks source link

Update-MdbcData and multiple update expressions #76

Closed codaamok closed 1 year ago

codaamok commented 1 year ago

I can update a document with multiple update expressions like so, no problem:

Update-MdbcData -Filter @{ _id = 'abc' } -Update @{ '$set' = @{ 'Passed' = 1 } }, @{ '$set' = @{ 'Failed' = 1 } }

However if I use a different operator, e.g. $inc, it gives me an exception:

PS C:\Users\acc> Update-MdbcData -Filter @{ _id = 'abc' } -Update @{ '$set' = @{ 'Passed' = 1 } }, @{ '$inc' = @{ 'Failed' = 10 } }

Update-MdbcData: Command update failed: Unrecognized pipeline stage name: '$inc'.
nightroman commented 1 year ago

Update-MdbcData help about the parameter Update:

-Update
    Specifies the update expression. The argument is JSON, similar dictionary, or array for aggregate expressions.

You use expression arrays as -Update values. Arrays are treated as aggregation pipeline expressions.

Docs: https://www.mongodb.com/docs/manual/tutorial/update-documents-with-aggregation-pipeline/

Aggregates include the operator $set, so your first command is supported. But $inc is not there, so the second command fails correctly.

What you probably want to do is update document expression (not aggregate expression). This should use a single document update expression.

Docs: https://www.mongodb.com/docs/manual/reference/operator/update/

Example, this works:

Import-Module Mdbc
Connect-Mdbc -NewCollection

@{_id='abc'; Passed=0; Failed=0} | Add-MdbcData

Update-MdbcData -Filter @{ _id = 'abc' } -Update @{ '$set' = @{ 'Passed' = 1 } }, @{ '$set' = @{ 'Failed' = 1 } }

# -Update is one @{...} with 2 fields
Update-MdbcData -Filter @{ _id = 'abc' } -Update @{ '$set' = @{ 'Passed' = 1 }; '$inc' = @{ 'Failed' = 10 } }

Get-MdbcData
codaamok commented 1 year ago

I just learned about aggregation pipelines, so thank you :-) this was my bad! thank you for taking the time to help.