nightroman / Mdbc

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

How to create indexes on a collection ? #56

Closed Khoosham closed 3 years ago

Khoosham commented 3 years ago

I have a collection where I need to create an index with a TTL on a specific field so that records are purged based on a retention period. Is it possible to create indexes on a collection using Mdbc ?

nightroman commented 3 years ago

There is no explicit Mdbc command for this. But you can do this either using MongoDB commands or C# API methods. Please explore MongoDB and C# driver manuals. (Mdbc is not supposed to wrap everything with its own commands).

Here is the example of using the MongoDB command createIndexes: https://github.com/nightroman/Mdbc/blob/117e27ca0e528f5d8be0c291d83492d49c43736e/Tests/HowTo.test.ps1#L8-L11

Khoosham commented 3 years ago

Ok i came up with the following command based on my needs and get the following error when trying to execute it Invoke-MdbcCommand : Cannot bind parameter 'Command' to the target. Exception setting "Command": "Cannot convert 'System.Management.Automation.ScriptBlock' to 'BsonValue'."

How can i fix this ?

$r = Invoke-MdbcCommand ([ordered]@{
    createIndexes = "mycollection"
    indexes = @(
        {
            key = @{
                    'ExpireAt.v' = 1
                }
            name = "ExpireAt"
            unique = false
            expireAfterSeconds = 180
        }
    )
  }) -Database $db
nightroman commented 3 years ago

In your indexes you pass the script block {...} but it should be a hashtable @{...}.

Khoosham commented 3 years ago

Thank you so much it worked. This is the final script incase someone else need the same.

$r = Invoke-MdbcCommand ([ordered]@{
    createIndexes = "mycollection"
    indexes = @(
        @{
            key = @{
                    'ExpireAt.v' = 1
                }
            name = "ExpireAt"
            unique = $false
            expireAfterSeconds = 180
        }
    )
  }) -Database $db