nightroman / Mdbc

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

Provide Upsert example #57

Closed awsles closed 3 years ago

awsles commented 3 years ago

Add-MdbcData allows you to add new documents. Set-MdbcData allows you to update existing documents.

Both of the above take a pipeline input. For example:

@{_id = 1; value = 42}, @{_id = 2; value = 3.14} | Add-MdbcData 
@{_id = 1; value = 55}, @{_id = 2; value = 66} | Set-MdbcData 

However, Update-MdbcData does not provide any obvious way to replace an entire document. It appears that individual properties can be updated using this cmdlet, but I've been unable to discover any syntax that allows an entire document to be replaced (and get-help Update-MdbcData does not provide any examples). Ideally, the behaviour I am hoping for is that if the document does not exist, that it is simply added. If it does exist, it is replaced.

The ask here is to provide a working example for replacing an existing document. Ideally though, Update-MdbcData should be consistent with the other cmdlets using a pipelined input. For example:

@{_id = 1; value = 42}, @{_id = 2; value = 3.14} | Add-MdbcData 
@{_id = 2} | Remove-MdbcData  # Remove 2nd item 
@{_id = 1; value = 77}, @{_id = 2; value = 88} | Update-MdbcData 
nightroman commented 3 years ago

Update-MdbcData does not provide any obvious way to replace an entire document. It appears that individual properties can be updated using this cmdlet, but I've been unable to discover any syntax that allows an entire document to be replaced (and get-help Update-MdbcData does not provide any examples).

Update-MdbcData updates fields, not whole documents. So what you are looking for is simply not there.

Set-MdbcData allows you to update existing documents.

By default. The switch -Add lets you to "upsert":

-Add
        Tells to add the new document if the old does not exist.

BTW, I would use the word "set" (PS standard) or "replace" (C# driver original) instead of "update" to avoid confusion.

nightroman commented 3 years ago

Provide Upsert example

I am not sure how to satisfy this request. There are no code names "upsert" anywhere. Even the C# driver has no such methods. But other methods have related options because the concept "upsert" still exists. Same or similar in Mdbc.

How do you see this example? An example for Set-MdbcData with -Add?

nightroman commented 3 years ago

All right. Here is the example of Upsert:

Import-Module Mdbc
Connect-Mdbc . test test -NewCollection

@{_id = 1; value = 42}, @{_id = 2; value = 3.14} | Add-MdbcData
@{_id = 2} | Remove-MdbcData  # Remove 2nd item
@{_id = 1; value = 77}, @{_id = 2; value = 88} | Set-MdbcData -Add  # Upsert
Get-MdbcData -As PS

Output:

_id value
--- -----
  1    77
  2    88