Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created March 19, 2020 04:40
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/81d591662ccf0e62cb467c4a91a4331a to your computer and use it in GitHub Desktop.
Save dj-nitehawk/81d591662ccf0e62cb467c4a91a4331a to your computer and use it in GitHub Desktop.
aggregation pipeline with multiple unwinds and replaceWith
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Linq;
namespace StackOverFlow
{
public class OptionMenu : Entity
{
public OptionMenuSubject[] subjects { get; set; }
}
public class OptionMenuSubject
{
public OptionMenuItem[] items { get; set; }
}
public class OptionMenuItem
{
public ObjectId id { get; set; }
public string name { get; set; }
}
public static class Program
{
private static void Main()
{
new DB("test", "localhost");
var pipeline = new Template<OptionMenu, OptionMenuItem>(@"
[
{
$match: {
'<subjects.items>._id': <item_id>
}
},
{
$unwind: '$<subjects>'
},
{
$unwind: '$<subjects.items>'
},
{
$match: {
'<subjects.items>._id': <item_id>
}
},
{
$replaceWith: '$<subjects.items>'
}
]")
.Path(m => m.subjects[0].items)
.Tag("item_id", "ObjectId('5e6eaef8ae35a418f4f6dbd4')")
.Path(m => m.subjects);
OptionMenuItem item = DB.Aggregate(pipeline)
.ToList()
.SingleOrDefault();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment