Search MongoDB and complex arrays

I have some 37K documents stored in Mongo that look something like this:

{
    "_id" : GUID,
    "Country" : "Germany",
    "TypeIds" : [47]
}


{
    "_id" : GUID,
    "Country" : "France",
    "TypeIds" : [54, 47]
}

Using the MongoDB C # driver and based on two sample entries, how can I request the following information:

  •   
  • All documents with TypeIds containing 47 or 54 must contain 2 entries  
  • All documents with TypeIds containing 47 AND 54 must contain 1 entry  
  • All documents with TypeIds containing 54 and the country "Germany" must contain 0 entries

Thanks,
Kiron

+3
source share
1 answer

You have a class like this (I just use GuidId.ToString () instead of guid):

public class Test
        {

            public Test()
            {
                TypeIds = new List<int>();
            }

            [BsonId]
            public string Id { get; set; }

            public string Country { get; set; }

            public List<int> TypeIds { get; set; }
        }

I inserted the rows in db according to the above docs

  var collection = db.Database.GetCollection("items");
            var id1 = Guid.NewGuid().ToString();
            var id2 = Guid.NewGuid().ToString();
            var test = new Test() { Id = id1, Country = "Germany" };
            test.TypeIds.Add(47);
            var test2 = new Test() { Id = id2, Country = "France" };
            test2.TypeIds.Add(54);
            test2.TypeIds.Add(47);
            collection.Insert(test);
            collection.Insert(test2);

Inquiries

//All documents that have TypeIds containing 47 or 54 - should result in 2 records
        var array = new List<int>() { 47, 54 };
        var condition1 = collection.FindAs<Test>(Query.In("TypeIds", BsonArray.Create(array))).ToList();

        //All documents that have TypeIds containing 54 AND a Country of 'Germany' - should result in 0 records
        var condition3 = collection.FindAs<Test>(Query.And(Query.EQ("TypeIds", 47), Query.EQ("Country", "Germany"))).ToList();

: :

//All documents that have TypeIds containing 47 AND 54 - should result in 1 records

     var array2 = new List<int>() { 47, 54 };
     var query = Query.All("TypeIds",BsonArray.Create(array2));

     var condition2 = collection.FindAs<Test>(query).ToList();
+3

Source: https://habr.com/ru/post/1788136/


All Articles