score:1
whatever you're trying to pass into .where()
method is an expression tree that needs to be translated into mongodb query language. c# compiler will accept expandoobject
's methods like singleordefault
(extension method) but this will fail in the runtime when such expression tree needs to be translated into mongo query.
there's nothing special about expandoobject
when you work with mongodb. it has to be translated somehow into bson document (mongodb format) and for example below code:
dynamic o = new expandoobject();
o.dateofbith = new datetime(2000, 1, 1);
r.contents = o;
col.insertone(r);
inserts expandoobject
same way as bsondocument
or dictionary<string, t>
so it simply becomes:
{ "_id" : objectid(",,,"), "contents" : { "dateofbith" : isodate("2000-01-01t07:00:00z") } }
in your database.
knowing that you can build your query using the dot notation. there's also a stringfielddefinition
class you can utilize since you cannot build an expression tree from expandoobject
in a strongly typed way:
var fielddef = new stringfielddefinition<record, datetime>("contents.dateofbith");
var filter = builders<record>.filter.gt(fielddef, new datetime(2000, 1, 1));
var res = col.find(filter).tolist();
score:1
these kind of expression transformations doesn't play well with linq how i see. tho if you go down 1 level to define the field as string, it will play better. than you can inject
your where
clause to keep iqueryable
if you like>
update (you can have multiple conditions, and different kinds of null checking)
string connectionstring = "mongodb://localhost:27017";
var client = new mongoclient(connectionstring);
var db = client.getdatabase("test");
var records = db.getcollection<record>("recorddata");
//dynamic content = new expandoobject();
//content.dateofbirth = datetime.today;
//records.insertone(new record
//{
// appname = "my app", created = datetime.today, createdby = "some user", formname = "form name",
// organisationid = "organization id", schemaversion = 1, version = "1.1", contents = content
//});
// first option for multiple conditions:
var filter =
builders<record>.filter.lt("contents.dateofbirth", datetime.now) &
builders<record>.filter.gt("contents.dateofbirth", datetime.now.adddays(-10)) &
// checking if the field is there. whether the value is null or not.
builders<record>.filter.exists("contents.dateofbirth") &
// checking if the field is there, and it's not null
builders<record>.filter.ne("contents.dateofbirth", bsonnull.value);
// second option for multiple conditions
var dateofbirths = records.asqueryable().where(_ => filter.inject()).where(x => x.appname == "my app").tolist();
from there, you can continue your iqueryable
syntax.
update 2
in case of .where(x => x.appname.contains("app"))
you'll get
"pipeline" : [
{
"$match" : {
"contents.dateofbirth" : {
"$exists" : true,
"$gt" : isodate("2020-05-15t12:48:14.483+02:00"),
"$lt" : isodate("2020-05-25t12:48:14.480+02:00"),
"$ne" : null
}
}
},
{
"$match" : {
"appname" : /app/g
}
}
]
from profiling the database. so the <string>.contains(<string>)
is implemented in iqueryable
as a regular expression filter not in memory.
Source: stackoverflow.com
Related Query
- Filtering using AsQueryable in Mongodb C# - ExpandoObject
- MongoDB C#Driver resp. Linq: query for unique instances and using static AsQueryable Properties
- Convert string[] to int[] in one line of code using LINQ
- C# - code to order by a property using the property name as a string
- How do I find the text within a div in the source of a web page using C#
- Entity-framework code is slow when using Include() many times
- filtering a list using LINQ
- How do I use the AsQueryable method asynchronously with MongoDb C# Driver 2.1?
- Filtering lists using LINQ
- Is AsQueryable method departed in new Mongodb C# driver 2.0rc?
- cannot do asqueryable on mongodb collection
- Get and Add/Update multilevel embedded/nested MongoDB document using C#
- Using C# MongoDB LINQ with discriminator
- Left outer join using LINQ -- understanding the code
- How to reuse a linq expression for 'Where' when using multiple source tables
- How to query if array is null or empty using MongoDB and C# Driver?
- Avoiding code repetition when using LINQ
- Filtering Windows logs using lambda expressions on non-IEnumerable types
- Using LINQ to delete an element from a ObservableCollection Source
- can my code improve from using LINQ?
- LINQ Source Code Available
- Filtering a nested collection using linq
- Sub-Query or Join with embedded/nested document using C# LINQ with MongoDB
- Using LINQ vs SQL for Filtering Collection
- .NET 4 Code Contracts: "requires unproven: source != null"
- List<int> filtering using linq
- How can I write the following code more elegantly using LINQ query syntax?
- MongoDB c# driver: Case Insensitive Compare using in or contains on a list using linq
- MongoDB C# driver: Using Linq to get Guid returns nothing
- How can I code an outer join using LINQ and EF6?
More Query from same tag
- Linq sql query Not implementing
- Search records with code pattern in column value c#
- How to combine to generic lists with add range and select criteria?
- Get Database values based on linq query
- Linq: aggregate results by group name
- C#, Entity Framework, How to Update(delete, add, edit) multiple rows at same time?
- Refactoring LINQ methods
- Linq - Is operations order relevant?
- Create custom object from List<T> using .Linq
- C# Sort array of objects by property name exists in the object
- ProtoBuf.NET - Choose fields you want to load at runtime
- Object reference not set to an instance of an object. Adding Two Table using LinQ in datagridview Entity Framework
- Discarding Intermediate results in Linq
- Set values for entities
- How to add an item to the repository without loading the item's Parent and siblings into memory
- Finding the difference between two lists of strings
- last integer in a string in linq
- Asp.net - how does it handle references to database rows?
- LINQ to SQL debug visualizer for VS 2012?
- Query and Assignment in a Single Step
- Select and Print list of PDF files from a folder
- LINQ for untyped IEnumerable
- How do I capture a variable in Linq method syntax?
- Group by range using linq
- How do detect non-existant rows in linq?
- VB.NET LINQ to DataSet (SQL 'LEFT OUTER JOIN' alternative)
- How to group and merge/flatten a list of anonymous objects in LINQ
- Help creating an instance of a class using Linq and XML
- C# exclude duplicate code from two method returning expression
- mapping from many-to-one in entity framework Core