Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query mongodb collection as dynamic

I'm saving a dynamic object in my database but I would also like to retrieve it as a dynamic object. How can this be done? I tried it like so:

public dynamic GetItemById(ObjectId id)
{
    dynamic result = Db.GetCollection<dynamic>("Items").Find(x => x.Id == id).FirstOrDefaultAsync().Result;
    return result;
}

But this gives me the following error:

CS1963 An expression tree may not contain a dynamic operation

I know this can be fixed by using a typed object instead of a dynamic one. But I don't want to use any typed objects, because that kind of defeats the entire purpose of using a NoSQL database like MongoDB (or at least, imho).

How can I query my collections by Id or any other property for that matter using dynamic objects?

like image 614
Vivendi Avatar asked Oct 26 '25 02:10

Vivendi


1 Answers

You can use the string-based syntax, since the expression doesn't offer any advantages with dynamic anyway:

var cursor = db.GetCollection<dynamic>("foo").
                Find(Builders<dynamic>.Filter.Eq("_id", someId));
like image 147
mnemosyn Avatar answered Oct 27 '25 17:10

mnemosyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!