【问题标题】:Get all objects where a property matches a value nested in array获取属性与嵌套在数组中的值匹配的所有对象
【发布时间】:2017-04-12 13:23:29
【问题描述】:

我有如下数据表:

{
"_id" : ObjectId("value"),
"owner" : "testuser",
"date" : ISODate("2017-03-16T12:45:03.386Z"),
"location" : "thuis",
"venue" : "bijna thuis",
"description" : "fghgfh",
"completed" : false,
"winnerName" : null,
"subscriptions" : [],
"interactions" : [ 
    {
        "_id" : ObjectId("objectid"),
        "owner" : "testuser",
        "type" : "guess",
        "date" : ISODate("2017-03-06T12:13:10.049Z"),
        "answer" : false,
        "message" : "test 1"
    }, 
    {
        "_id" : ObjectId("objectid"),
        "owner" : "testuser",
        "type" : "guess",
        "date" : ISODate("2017-03-06T12:13:10.049Z"),
        "answer" : false,
        "message" : "test 2"
    }
],
"__v" : 0,
"active" : true

}

以上只是一个游戏对象。这意味着我们的数据库中有几个这样的对象。 我试图只获得所有者==“testuser”的交互。 问题是我似乎无法找出最好的方法来做到这一点。 在我的代码中,我得到了 2 个对象(游戏和交互),其中 Game 有一系列交互。

有没有办法我仍然可以使用 mongocsharpdriver 做到这一点。

提前感谢所有帮助。

【问题讨论】:

    标签: mongodb asp.net-core mongodb-.net-driver


    【解决方案1】:

    希望它对你有用谢谢:-)

    collection.Find(x => x.owner == "testuser").ToList(); //where collection is MongoDB collection
    

    【讨论】:

      【解决方案2】:

      感谢所有建议,对于迟到的回复深表歉意。但我找到了一种解决方法:

      var filter = Builders<Game>.Filter.ElemMatch("interactions",
                  Builders<Interaction>.Filter.Eq("owner", owner));
              var interactions = await MongoCollection.Find(filter).ToListAsync();
      
              return interactions.SelectMany(item => item.Interactions).ToList();
      

      这将返回以特定用户为所有者的所有交互。 希望我可以帮助某人回答这个问题。

      【讨论】:

        猜你喜欢
        • 2013-10-11
        • 1970-01-01
        • 2013-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        相关资源
        最近更新 更多