Get all objects where a property matches a value n

2019-07-17 18:59发布

问题:

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.