MongoDB and Complex Array Search
I've some 37K documents stored in Mongo that looks similar to these:
{
"_id" : GUID,
"Country" : "Germany",
"TypeIds" : [47]
}
{
"_id" : GUID,
"Country" : "France",
"TypeIds" : [54, 47]
}
Using the MongoDB C# driver, and based on the two example records, how can I query for the following information:
- All documents that have TypeIds containing 47 or 54 - should result in 2 records
- All documents that have TypeIds containing 47 AND 54 - should result in 1 records
- All documents that have TypeIds containing 54 AND a Country of 'Germany' - should result in 0 rec开发者_Python百科ords
Thanks,
KieronYou have class like this(i just instead of guid use GuidId.ToString()):
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've inserted rows into db according above documents
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);
Queries:
//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();
Update: I found way to do second condition:
//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();
精彩评论