I have a collections called storeinventories in Mongodb. I am trying to perform following MQL query in the C# code.
The storeinventories collection has the following data model.
{
"_id":"12938192831928",
"ItemName":"Coke 20Oz",
"Price":{
"$numberInt":"-1"
},
"Cost":{
"$numberInt":"-1"
},
"DeptId":"Coke",
"CreatedDate": "02/02/2020"
}
db.storeinventories.aggregate([
{
"$search": {
"autocomplete": {
"query": "item",
"path": "ItemName",
"fuzzy": {
"maxEdits": 2,
"prefixLength": 3
}
}
}
},
{
$project: {
"_id": 0,
"ItemName": 1,
"Price": 1,
"Cost": 1
}
}
])
This is what the InventoryAutoComplete class looks like. I am currently using BsonIgnoreExtraElements to ignore any field that I do not have in this class.
namespace inventory.service.Data
{
[BsonIgnoreExtraElements]
public class InventoryAutoComplete
{
public string Id { get; set; }
public string ItemName { get; set; }
public decimal Cost { get; set; }
public decimal Price { get; set; }
}
}
Disclaimer: I am trying to find more Linq way to do my below query that I am doing to get the list from my query. Please feel free to give me better version of this if there is anything that we can improve with this.
I have two questions
How to Aggregate and Project like I have with MQL? I do currently use AggregateAsync to aggregate pipeline with MQL query. I was wondering if there is anytthing I can improve with the query.
Would Mongdb driver be smart enought to figureout to not fetch any other properties from server when I have
BsonIgnoreExtraElementswith a class?
var pipeline = new []
{
new BsonDocument {
{
"$search",
new BsonDocument( "autocomplete", new BsonDocument("path", "ItemName").AddRange(new BsonDocument("query", term)))
}
},
new BsonDocument("$limit", 10)
new BsonDocument
{
{
"$project",
new BsonDocument("ItemName", 1)
//TODO: List all the properties that we have in the InventoryAutoComplete that we want to map.
// We do not want MongoDrive to fetch unneeded properties like `DeptId` and `CreatedDate`
// Currently, the 'BsonIgnoreExtraElements' will take care of ignoring other needed properties
}
}
};
//StoreInventories is type 'IMongoCollection'
var list = await _inventoryContext
.StoreInventories
.AggregateAsync<InventoryAutoComplete>(pipeline);