قالب وردپرس درنا توس
Home / Tips and Tricks / Using LiteDB in PowerShell 7 – CloudSavvy IT

Using LiteDB in PowerShell 7 – CloudSavvy IT



Powershell logo

LiteDB is a .NET native NoSQL embedded database. Built-in .NET, LiteDB is easily accessible to PowerShell and works great as a local and flexible database. Built-in encryption, SQL-like commands and ACID compliant with full transaction support LiteDB is simple and easy to use. In this article, we’ll talk about how to use LiteDB in PowerShell and possible use cases!

Install LiteDB in PowerShell

LiteDB is available as a NuGet package and can be easily installed as a package with the Install-Package cmdlet. The latest version, at the time of publication, is version 5.0.9, which we focus on as the minimum version. In addition, to avoid the need for administrator rights, we install this under the CurrentUser scope.

Install-Package -Name 'LiteDB' -MinimumVersion '5.0.9' -Source 'nuget.org' -Scope 'CurrentUser'

Next, we are going to import the library for use. You can just use Add-Type and point to the path of the assembly, but we can automate that.

# Test if we have already loaded the assembly by looking for the PSType of LiteDB.LiteDatabase
If ( -Not ([System.Management.Automation.PSTypeName]'LiteDB.LiteDatabase').Type ) {
	# 1
) Get the path of the LiteDB package using the Source # 2) This returns the *.nupkg file, so we use Split-Path to only return the package root path # 3) Multiple DLL's will exist, usually for .NET 4.5, .NET Standard 1.3, and .NET Standard 2.0. Locate only the .NET Standard and the latest version, in this case 2.0. # The path will look something like: C:\Users\username\AppData\Local\PackageManagement\NuGet\Packages\LiteDB.5.0.9\lib\netstandard2.0\LiteDB.dll $standardAssemblyFullPath = (Get-ChildItem -Filter '*.dll' -Recurse (Split-Path (Get-Package -Name 'LiteDB').Source)).FullName | Where-Object {$_ -Like "*standard*"} | Select-Object -Last 1 Add-Type -Path $standardAssemblyFullPath -ErrorAction 'SilentlyContinue' }

Now that we’ve loaded the module for use, read on to create a new LiteDB database in the next section!

Create a new LiteDB database

There are a number of commands available for LiteDB, which you can learn more about here, but we need to create a completely new database first. We will have to define the path where to create the database file. Since LiteDB creates single file databases, the database can be located anywhere. In this case, we are looking for the DB in our current path and using the name of Test.db.

# Create the Test.db database in the current directory
$Database = [LiteDB.LiteDatabase]::New((Join-Path -Path "." -ChildPath "Test.db"))

Keep that in mind until you call $Database.Dispose() on the database file, the Test.db file remains locked.

In the next section we will create a table, add an index and create a new record in our database.

Create a table and add a record to LiteDB

As with tables in SQL, LiteDB uses collections, similar to MongoDB. For this article, we are creating a new collection called TestCollection, and by using GetCollection() the collection is created if it does not already exist.

# Retrieve the collection (i.e. table) to store our data in.
$Collection = $Database.GetCollection('TestCollection')

# Make sure that an index exists on the Name field so that queries work easier and quicker.
# To allow for named queries, such as using the Name field, we ensure an index is created.
# The result is sent to Out-Null to avoid the True console output on creation.
$Collection.EnsureIndex('Name') | Out-Null

Indexes are valuable because they improve performance and allow for easily named searches when looking for a record. Implemented using skip lists, indexes avoid a full scan and deserialization of the database every time a search is performed.

Add a record to a LiteDB collection

First we have to LiteDB.BSONMapper. This is LiteDB’s implementation of documents, in which key-value pairs are stored. We first create a mapper that we can parse a PowerShell object into a document that can then be added to our collection with the Insert() method.

$BSONMapper = [LiteDB.BSONMapper]::New()

$Object = @{
  "Name"  = 'TestName'
  "Value" = 'TestValue'
}

Try {
  # Attempt to insert the object as a new collection entry.
  $Collection.Insert($BSONMapper.ToDocument($Object))
} Catch {
  Throw "Unable to insert item."
}

Query records in LiteDB

To query an object in LiteDB we can use several methods such as:

  • FindAll() – Return all documents in a collection.
  • FindOne() – Returns FirstOrDefault of a Find() ask.
  • FindById() – Returns SingleOrDefault result of Find() by using the primary key of _id index.
  • Find() – Return all documents with the defined expression.

In this example, let’s get all the documents and then just the one we’re looking for. We can also test whether the document exists using the Exists() method. To prove this, we will first check if the document exists, and then find the first document with the name TestName and finally find all the documents. To demonstrate the latter method, we added an additional document with the same name but a different value.

# Test if the `TestName` document exists
$Collection.Exists("`$.Name="TestName"")
# Return the first `TestName` document found
$Collection.FindOne("`$.Name="TestName"")
# Display all documents in a collection
$Collection.FindAll()

Check if the document exists, find the specific document and then all documents.

Update and delete a document

Now that we have created a document, let’s update the value. This is done with the appropriate name Update() method.

$Item = $Collection.FindOne("`$.Name="TestName"")

$Item['Value'] = 'UpdatedValue'

Try {
  # Attempt to update the existing document with the updated value
  $Collection.Update($Item)
} Catch {
  Throw "Unable to update item."
}

We may not want to keep this document. Therefore, we can delete the document with the Remove() method. This requires that we know the ID of the document. Because we already have the information in it $Item variable, we can change the _id property to delete the document.

Try {
	# Remove the entry using the _id attribute, internal to the LiteDB database
	$Collection.Delete($Item['_id'].RawValue)
} Catch {
	Throw "Unable to delete item."
}

Cleaning up the database and next steps

Since the database is locked in use, we need to use the Dispose() method to remove the lock. This is an important step, otherwise we could end up with corruption.

$Database.Dispose()

With that, we demonstrated end-to-end examples of how to create a database, create and update documents, and delete those documents. There are many possible uses for LiteDB, from a temporary data collection database on a server to a fast and portable document storage system that can be easily backed up. Discover LiteDB and see what you can do with it today!


Source link