LiteDB is a .NET native NoSQL embedded database. Constructed-in .NET, LiteDB is without bother accessible to PowerShell and works wonderfully as a local and versatile database. Constructed-in encryption, SQL-be pleased commands, and ACID-compliant with paunchy transaction pork up LiteDB is easy and simple to make utilize of. On this article, we can focus on about possibilities are you’ll utilize LiteDB within PowerShell and attainable utilize cases!
Installing LiteDB in PowerShell
Accessible as a NuGet equipment, LiteDB is without bother installable as a equipment using the Install-Kit
cmdlet. The latest model, at the time of newsletter, is model 5.0.9
, which we are concentrating on because the minimum model. Moreover, to handbook some distance off from the need for administrative rights, we are putting in this below the CurrentUser
scope.
Install-Kit -Title 'LiteDB' -MinimumVersion '5.0.9' -Supply 'nuget.org' -Scope 'CurrentUser'
Next, we are going to import the library for utilize. You would merely utilize Add-Kind
and narrate the move of the assembly, but we are in a position to automate that.
# Take a look at if we enjoy already loaded the assembly by taking a end wakeful for the PSType of LiteDB.LiteDatabase
If ( -Not ([System.Management.Automation.PSTypeName]'LiteDB.LiteDatabase').Kind ) {
# 1) Bag the move of the LiteDB equipment using the Supply
# 2) This returns the *.nupkg file, so we utilize Split-Route to totally return the equipment root course
# 3) Loads of DLL's will exist, normally for .NET 4.5, .NET Long-established 1.3, and .NET Long-established 2.0. Discover fully the .NET Long-established and the most up-to-date model, in this case 2.0.
# The move will review something be pleased: C:\Customers\username\AppData\Local\PackageManagement\NuGet\Applications\LiteDB.5.0.9\lib\netstandard2.0\LiteDB.dll
$standardAssemblyFullPath = (Bag-ChildItem -Filter '*.dll' -Recurse (Split-Route (Bag-Kit -Title 'LiteDB').Supply)).FullName | Where-Object {$_ -Love "*long-established*"} | Take-Object -Final 1
Add-Kind -Route $standardAssemblyFullPath -ErrorAction 'SilentlyContinue'
}
Now that we enjoy loaded the module for utilize, learn on to form a brand aloof LiteDB database within the next allotment!
Constructing a Contemporary LiteDB Database
There are a set of commands available for LiteDB, which possibilities are you’ll uncover about right here, but we first must form a tag aloof database. We’re going to must define the move the place to form the database file. Since LiteDB creates single file databases, the database will be positioned anyplace. On this case, we can detect the DB in our recent course and utilize the identify of Take a look at.db
.
# Manufacture the Take a look at.db database within the recent directory
$Database = [LiteDB.LiteDatabase]::Contemporary((Join-Route -Route "." -ChildPath "Take a look at.db"))
Abet in mind that till you call
$Database.Dispose()
on the database file, theTake a look at.db
file will remain locked.
In the next allotment we can form a desk, add an index, and form a brand aloof file in our database.
Constructing a Desk and Including a Tale into LiteDB
Equivalent to tables in SQL, LiteDB uses Collections, corresponding to MongoDB. For this article, we can form a brand aloof collection named TestCollection
, and by utilizing GetCollection()
the gathering will be created if it doesn’t already exist.
# Retrieve the gathering (i.e. desk) to retailer our details in.
$Assortment = $Database.GetCollection('TestCollection')
# Make certain that an index exists on the Title arena so that queries work less complicated and quicker.
# To enable for named queries, much like using the Title arena, we make traipse an index is created.
# The end result is disbursed to Out-Null to handbook some distance off from the Factual console output on advent.
$Assortment.EnsureIndex('Title') | Out-Null
Indexes are treasured as they boost performance and enable for without bother named queries when browsing for a file. Implemented using skip-lists, indexes steer some distance off from a paunchy-scan and deserialization of the database at any time when a search is done.
Including a Tale Correct into a LiteDB Assortment
First, we must put collectively the LiteDB.BSONMapper
. That is LiteDB’s implementation of paperwork, which stores key-label pairs. We first form a mapper that we are in a position to parse a PowerShell object true into a doc that can then be added to our collection using the Insert()
formula.
$BSONMapper = [LiteDB.BSONMapper]::Contemporary()
$Object = @{
"Title" = 'TestName'
"Brand" = 'TestValue'
}
Strive {
# Strive to insert the item as a brand aloof collection entry.
$Assortment.Insert($BSONMapper.ToDocument($Object))
} Interact {
Throw "Unable to insert merchandise."
}
Querying Records in LiteDB
To query an object in LiteDB, we are in a position to utilize various diversified recommendations much like:
FindAll()
– Return all paperwork in a set.FindOne()
– ReturnsFirstOrDefault
of aGain()
query.FindById()
– ReturnsSingleOrDefault
outcomes ofGain()
by utilizing the principal key of_id
index.Gain()
– Return all paperwork using the outlined expression.
On this case, let’s query the total paperwork after which apt the one who we are taking a end wakeful for. We also can check if the doc exists, using the Exists()
formula. To level this, we can first check that the doc exists, then detect the first doc with the identify TestName
and finally detect all paperwork. To level the final formula, we enjoy added an additional doc of the identical identify but a special label.
# Take a look at if the `TestName` doc exists
$Assortment.Exists("`$.Title = 'TestName'")
# Return the first `TestName` doc found
$Assortment.FindOne("`$.Title = 'TestName'")
# Insist all paperwork in a set
$Assortment.FindAll()
Take a look at that the doc exists, positioned the explicit doc, after which all paperwork.
Updating and Getting rid of a Doc
Now that we enjoy created a doc, let’s change the price. That is done using the aptly named Update()
formula.
$Merchandise = $Assortment.FindOne("`$.Title = 'TestName'")
$Merchandise['Value'] = 'UpdatedValue'
Strive {
# Strive to change the aloof doc with the as much as the moment label
$Assortment.Update($Merchandise)
} Interact {
Throw "Unable to change merchandise."
}
No doubt, we might honest now now not must preserve this doc. Due to the this fact, we are in a position to seize away the doc using the Use away()
formula. This requires us to perceive the ID of the doc. Since we already enjoy the knowledge within the $Merchandise
variable, we are in a position to leverage the _id
property to seize away the doc.
Strive {
# Use away the entry using the _id attribute, internal to the LiteDB database
$Assortment.Delete($Merchandise['_id'].RawValue)
} Interact {
Throw "Unable to delete merchandise."
}
Cleansing up the Database and Next Steps
Since the database is locked when in utilize, we must call the Dispose()
formula to seize away the lock. That is a wanted step, in every other case, we might honest find yourself with corruption.
$Database.Dispose()
With that, we enjoy demonstrated end-to-end examples of creating a database, creating and updating paperwork, and laying aside those paperwork. There are quite about a attainable uses for LiteDB, much like a non everlasting details collection database on a server, to a fast and transportable doc storage machine which might be without bother backed up. Discover LiteDB and peep what possibilities are you’ll attain with it this day!