Search code examples
mongodbc#-4.0mongodb-querymongodb.driver

Get all items where subDocument.value in listOfStrings


I am using the MongoDB.Driver nuget package in dotnetcore 2.1. I am trying to return a list of documents in a collection where a subdocument field is equal to any items contained within a list that I have. Ideally I need this in C# syntax for the MongoDB.Driver nuget package for dotnetcore 2.1.

Document { "_id" : "e29628a65e914c1e91b3fd9cbf6f2353", "Enabled" : true, "Name" : "Document123", "DisplayName" : "Some Document", "Description" : "Some Description", "Data" : [ "lastname", "email", "firstname", "zipcode" ], "Items" : [ { "_id" : "1", "Name" : "bob" }, { "_id" : "2", "Name" : "smith" } ] }

If this were SQL, here is what I am trying to do:

SELECT * FROM Document a, Item b WHERE a.Id = b.DocumentId AND b.Name IN ('bob', 'smith', 'alex')

Here is what we have that is not working with the MongoDB driver:

string[] names = new [] { "bob", "smith", "alex" };
var document = new BsonDocument()
{
                new BsonElement("Items.Name", new BsonDocument()
                {
                    new BsonElement("$in", new BsonArray(names))
                })
            };
var itemsQuery = collection
                .Aggregate()
                .Match(document)
                ;

            var items = itemsQuery.ToList();

Thanks in advance.


Solution

  • It turns out we had to "unwind" and run a match query after this. Here is the code that worked for us.

            var collection = GetCollection<Document>();
    
            var document = new BsonDocument()
            {
                new BsonElement("Name", "Document123"),
                new BsonElement("Items.Name", new BsonDocument()
                {
                    new BsonElement("$in", new BsonArray(new [] { "bob", "smith", "alex"}))
                })
            };
    
            var itemsQuery = collection
                .Aggregate()
                .Unwind(d => d.Items)
                .Match(document)
                ;
    
            var items = itemsQuery.ToList();