3

Mongoに保存されている37Kのドキュメントは、次のようになります。

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


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

MongoDB C#ドライバーを使用し、2つのサンプルレコードに基づいて、次の情報をクエリするにはどうすればよいですか。

  1. 47または54を含むTypeIdを持つすべてのドキュメント-結果は2レコードになります
  2. 47と54を含むTypeIdを持つすべてのドキュメント-結果は1レコードになります
  3. 54と「ドイツ」の国を含むTypeIdを持つすべてのドキュメント-結果は0レコードになるはずです

ありがとう、
キエロン

4

1 に答える 1

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

上記のドキュメントに従ってdbに行を挿入しました

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

更新:2番目の条件を実行する方法を見つけました:

//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();
于 2011-01-27T09:12:13.563 に答える