Get all objects where a property matches a value nested in array

我的未来我决定 提交于 2019-12-10 22:24:52

问题


I have the following data table:

{
"_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

}

The above is just one game object. Which means we got several of this objects in our database. I am trying to get only the interactions where the owner == "testuser". The problem is that I cannot seem to figure out the best way to do this. In my code I got 2 objects ( Game & Interaction) where Game has an array of interactions.

Is there someway I can still do this using the mongocsharpdriver.

Thanks in advance for all the help.


回答1:


Hope it work for you Thanks :-)

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



回答2:


Thanks for all the suggestions and sorry for the late response. But I find a way to solve it like this:

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

This will it will return all the interactions that has a certain user as owner. Hope I can help somebody out with this answer.



来源:https://stackoverflow.com/questions/43370829/get-all-objects-where-a-property-matches-a-value-nested-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!