Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Last active March 9, 2020 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/bda542ca93609fe12a670ccab89dc1d2 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/bda542ca93609fe12a670ccab89dc1d2 to your computer and use it in GitHub Desktop.
aggregate - match > sort > group > replacewith
using MongoDB.Driver;
using MongoDB.Entities;
using MongoDB.Entities.Core;
using System;
using System.Linq;
namespace StackOverFlow
{
public class Product : Entity
{
public int NonUniqueId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public static class Program
{
private static void Main()
{
new DB("test", "localhost");
var pipeline = new Template<Product>(@"
[
{
$match: { <Name>: '<product_name>' }
},
{
$sort: { <Price>: 1 }
},
{
$group: {
_id: '$NonUniqueId',
product: { $first: '$$ROOT' }
}
},
{
$replaceWith: '$product'
},
{
$limit: <limit_value>
}
]")
.Path(p => p.Name)
.Tag("product_name", "book")
.Path(p => p.Price)
.Tag("limit_value", "10");
var products = DB.Aggregate(pipeline).ToList();
foreach (var p in products)
{
Console.WriteLine($"product: {p.Name} | price: {p.Price}");
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment