如何在mongodb中查询子文档

时间:2014-10-30 05:29:47

标签: c# 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的原因。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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 result = program.Find(query);