Search code examples
c#mongodbmongodb-.net-driver

Mongodb C# - aggregation $push only if nested element of the nested array match the condition


I already looked a lot on the internet before asking, but I couldn't find out a solution...

There is a example of my classes and objects:

Classes:

public class A {
    [BsonId]
    public int _id {get; set;}
    public List<B> ListOfB {get; set;}
    public TypeA Type {get; set;}
}

public class B {
    public int _id {get; set;}
    public int PersonId {get; set;}
    public Person Person {get; set;} // This one is not save on the DB, it is retrieved through a Lookup
    public int Type {get; set;}
}

public class Person {
    [BsonId]
    public int _id {get; set;}
    public string Name {get; set;}
}

Objects:

{
    "_id": 0;
    "Type", 0,
    "ListOfB": [
        {
            "_id": 0,
            "PersonId": 300,
            "Type": 0
        },
        {
            "_id": 1,
            "PersonId": 24,
            "Type": 0
        },
        {
            "_id": 2,
            "PersonId": 59,
            "Type": 1
        }
    ]
},
{
    "_id": 1;
    "Type", 1,
    "ListOfB": [
        {
            "_id": 0,
            "PersonId": 45,
            "Type": 1
        },
        {
            "_id": 1,
            "PersonId": 102,
            "Type": 0
        },
        {
            "_id": 2,
            "PersonId": 33,
            "Type": 1
        }
    ]
}
,
{
    "_id": 2;
    "Type", 1,
    "ListOfB": [
        {
            "_id": 0,
            "PersonId": 66,
            "Type": 1
        },
        {
            "_id": 1,
            "PersonId": 89,
            "Type": 0
        },
        {
            "_id": 2,
            "PersonId": 404,
            "Type": 0
        }
    ]
}

B is part of the A collection, there is no collection of B. So far I have done something like this to retrieve the objects:

BsonDocument groupMappingA = new BsonDocument();
groupMappingA.Add(new BsonElement("_id", "$_id"));

BsonDocument groupMappingB = new BsonDocument();
groupMappingB.Add(new BsonElement("_id", "$ListOfB._id"));
groupMappingB.Add(new BsonElement("PersonId", "$ListOfB.PersonId"));
groupMappingB.Add(new BsonElement("Person", "$ListOfB.Person"));
groupMappingB.Add(new BsonElement("Type", "$ListOfB.Type"));

groupMappingA.Add(new BsonElement("ListOfB", new BsonDocument(
                                                "$push", new BsonDocument(
                                                        "$cond", new BsonArray {
                                                            new BsonDocument("$eq", new BsonDocument("$ListOfB.Type", "0")),
                                                            new BsonDocument("$ListOfB", groupMappingB)
                                                        }
                                                )
                                            )
                                )
                );

AggregateUnwindOptions<A> unwindOptions = new AggregateUnwindOptions<A>() { PreserveNullAndEmptyArrays = true };
db.GetCollection<A>("A").Aggregate()
                        .match(x => x.Type == 1)
                        .Unwind("ListOfB", unwindOptions)
                        .Lookup("Person", "ListOfB.PersonId", "_id", "ListOfB.Person") // Here we set up Person through the ID saved in the object B
                        .Unwind("ListOfB.Person", unwindOptions)
                        .Group(groupMappingA)
                        .As<A>()
                        .ToList();

So what I am trying to achieve is to retrieve all the objects A, and filtering all their B objects to get only the ones with their Type equals to 0, and for each of the objects B, I should have the Person, such as:

{
    "_id": 1;
    "Type", 1,
    "ListOfB": [
        {
            "_id": 1,
            "PersonId": 102,
            "Type": 0,
            "Person": { "_id": 102, "Name": "Billy" } 
        }
    ]
},
{
    "_id": 2;
    "Type", 1,
    "ListOfB": [
        {
            "_id": 1,
            "PersonId": 89,
            "Type": 0,
            "Person": { "_id": 89, "Name": "Finn" }
        },
        {
            "_id": 2,
            "PersonId": 404,
            "Type": 0,
            "Person": { "_id": 404, "Name": "Jake" }
        }
    ]
}

But this doesn't work... I can retrieve each A objects of Type 1, with all the Person objects in their B Objects, but I get the full list of B, not only the ones of type 0.

I tried to do it on Mongodb Compass first, but so far, I did not succeed, then I looked on the internet, but I couldn't find what I am looking for... I started to wonder if it is even possible to get an objects with a filter on its nested list ?

Thank you in advance for your help.


Solution

  • I found out how to do it, I'm posting the answer here in case someone ever need it.

    BsonDocument groupMapping = new BsonDocument();
    groupMapping.Add(new BsonElement("_id", new BsonDocument("$first", "$_id")));
    groupMapping.Add(new BsonElement("ListOfB", new BsonDocument("$push", "$ListOfB")));
    
    AggregateUnwindOptions<A> unwindOptions = new AggregateUnwindOptions<A>() { PreserveNullAndEmptyArrays = true };
    db.GetCollection<A>("A").Aggregate()
                            .match(x => x.Type == 1)
                            .Unwind("ListOfB", unwindOptions)
                            .Match(new BsonDocument("ListOfB.Type", 0)) // Just put a match right after the Unwind, you'll be able to filter the elements of the list as you want.
                            .Lookup("Person", "ListOfB.PersonId", "_id", "ListOfB.Person")
                            .Unwind("ListOfB.Person", unwindOptions)
                            .Group(groupMapping)
                            .As<A>()
                            .ToList();