How do I write a query in MongoDB that gives me all documents that contain all specified nested documents?

105 views Asked by At

enter image description here

Say I had a MongoDB document with 2 embedded documents stored in the Array "AD". Each of these embedded documents will have specific data that I need to match. How would I write a query to find this document?

In the C# driver I'm currently writing it like this:

var q1 = Query.And(
    Query.EQ("AD.ABC1", "123"),
    Query.EQ("AD.YOB", "1969")
);

var q2 = Query.And(
    Query.EQ("AD.ABC1", "456"),
    Query.EQ("AD.YON", "1970")
);

var query = Query.And(q1, q2);

Which gives me a query of:

{
    "$and": [
        {
            "AD.ABC1": "123"
        },
        {
            "AD.YOB": "1969"
        },
        {
            "AD.ABC1": "456"
        },
        {
            "AD.YON": "1970"
        }
    ]
}

This returns documents that have embedded documents that match EITHER q1 or q2. I want the intersection of this - ie documents that have embedded documents that match BOTH q1 AND q2.

Thanks

1

There are 1 answers

0
millarnui On

Worked it out

var q1 = Query.ElemMatch("AD",
    Query.And(
        Query.EQ("ABC1", "123"),
        Query.EQ("YOB", "1969")
    )
);

var q2 = Query.ElemMatch("AD",
    Query.And(
        Query.EQ("ABC1", "456"),
        Query.EQ("YOB", "1970")
    )
);

var query = Query.And(q1, q2);

which gives me

{
"$and": [
    {
        "AD": {
            "$elemMatch": {
                "ABC1": "123",
                "YOB": "1969"
            }
        }
    },
    {
        "AD": {
            "$elemMatch": {
                "ABC1": "456",
                "YOB": "1970"
            }
        }
    }
]
}