2014-10-30 169 views
0
我有以下集合包含程序的列表,包含會話的列表中的每個程序

如何查詢子文檔中的mongodb

{ 
    "_id" : ObjectId("543f6fd8a4490a19b42c84eb"), 
    "Name" : "Program1", 
    "Tags" : "Tag1,Tag2", 
    "Sessions" : [{ 
     "_id" : ObjectId("544a00716c6d791820c2d1ae"), 
     "Name" : "Session1", 
     "Tags" : "Tag1,Tag2" 
    },{ 
     "_id" : ObjectId("544e426dbb63bc0d94d7ad81"), 
     "Name" : "Session2", 
     "Tags" : "Tag1,Tag2" 
    }] 
}, 
{ 
    "_id" : ObjectId("544e42a1bb63bc0d94d7ad82"), 
    "Name" : "Program2", 
    "Tags" : "Tag1,Tag2", 
    "Sessions" : [{ 
     "_id" : ObjectId("543f6fd8a4490a19b42c84eb"), 
     "Name" : "Session1", 
     "Tags" : "Tag1,Tag2" 
    },{ 
     "_id" : ObjectId("544e4cb1bb63bc0d24333b04"), 
     "Name" : "Session2", 
     "Tags" : "Tag1,Tag2" 
    }] 
} 

現在查詢程序我根本就如下:

var program = _db.GetCollection<Program>("Program"); 
IMongoQuery _query = Query<Program>.Where(e => e.Name.Contains("Program")); 
programCursor = MongoCursor program.Find(_query).SetSortOrder(SortBy.Ascending("Name")).SetLimit(ItemsPerPage).SetSkip(ItemsPerPage * (PageNo - 1)); 

現在如果我想查詢哪個子文檔的會話。假設我有程序ID和會話名稱,我將如何查詢mongodb c#中的子文檔。在這種情況下我沒有找到太多幫助,這就是爲什麼我發佈這個SO。

+0

與論壇網站不同,我們不使用「謝謝」,或「任何幫助表示讚賞」,或在[so]上簽名。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed - 從 - 個)。 – 2014-10-30 05:34:09

回答

0

您可以使用

IMongoQuery _query1 = Query<Program>.ElemMatch(e => e.Sessions, builder => builder.Matches(session => session.Name, "/.*" + search_phrase + ".*/")); 

IMongoQuery _query2 = Query<Program>.ElemMatch(e => e.Sessions, builder => builder.Where(session => session.Name.Contains(search_phrase))); 

,您可以或者爲您查詢

var query = Query.Or(new BindingList<IMongoQuery> 
{ 
    _query, 
    _query1, 
    .... 
}); 

VAR的結果= program.Find(查詢) ;

1

您可以使用下面的查詢:

{"_id" : ObjectId("543f6fd8a4490a19b42c84eb"),"Sessions.Name":"Session2"} 

輸出:

{ 
    "_id" : ObjectId("543f6fd8a4490a19b42c84eb"), 
    "Name" : "Program1", 
    "Tags" : "Tag1,Tag2", 
    "Sessions" : [{ 
     "_id" : ObjectId("544a00716c6d791820c2d1ae"), 
     "Name" : "Session1", 
     "Tags" : "Tag1,Tag2" 
    }, { 
     "_id" : ObjectId("544e426dbb63bc0d94d7ad81"), 
     "Name" : "Session2", 
     "Tags" : "Tag1,Tag2" 
    }] 
} 

,或者可以使用聚合獲取單個會話對象:

db.collection_name.aggregate([ 
    { $unwind : "$Sessions" }, 
    { $match : {"_id" : ObjectId("543f6fd8a4490a19b42c84eb"),"Sessions.Name":"Session2"} } 
]); 

輸出:

{ 
    "result" : [ 
     { 
      "_id" : ObjectId("543f6fd8a4490a19b42c84eb"), 
      "Name" : "Program1", 
      "Tags" : "Tag1,Tag2", 
      "Sessions" : { 
       "_id" : ObjectId("544e426dbb63bc0d94d7ad81"), 
       "Name" : "Session2", 
       "Tags" : "Tag1,Tag2" 
      } 
     } 
    ], 
    "ok" : 1 
}