MongoDB和复杂数组搜索

时间:2011-01-27 08:51:50

标签: .net-4.0 mongodb mongodb-.net-driver

我在Mongo中存储了一些看似类似的37K文档:

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


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

使用MongoDB C#驱动程序,并基于两个示例记录,如何查询以下信息:

        
  1. 所有包含47或54的TypeIds的文档应该会产生2条记录
  2.     
  3. 所有包含47和54的TypeIds的文档应该会产生1条记录
  4.     
  5. 所有TypeIds包含54且国家/地区为'德国'的文档应该会产生0条记录
  6. 谢谢,
    基隆

1 个答案:

答案 0 :(得分:3)

你有这样的课(我只是代替guid使用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; }
        }

我已根据上述文件将行插入数据库

  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);

查询:

//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();