Reputation: 1525
In MongoDb Compass I can query a collection like the following:
{ age: { $eq: "65", $eq: 65} }
As you might ask - I don't know if age is a string or number.
How can I make such a query in c#?
I tried a IEnumerable<KeyValuePair<string, object>> and give this to a BsonDocument - but I get an error with duplicate keys which is obvious cause there are two $eq operators.
But how to do it right in c#?
var para = comparisonOperator.Parameter.Name;
var op = FilterComparisonOperators.GetComparisonMongoDbOperator(comparisonOperator.Name);
var value = comparisonOperator.Value.Name;
if (int.TryParse(value, out int intValue))
{
var bsonDocument = new BsonDocument(op, intValue);
filterDocument.AddRange(new BsonDocument(para, bsonDocument));
filterDocument.AddRange(new BsonDocument(para, bsonDocument));
}
else
{
var bsonDocument = new BsonDocument(op, value);
filterDocument.AddRange(new BsonDocument(para, bsonDocument));
}
I want to query a number like 65 as number or string.
Upvotes: 0
Views: 38
Reputation: 15235
You can use $or
like this query or $in
like this other query so you can try something like this in Linq way:
Using $or
(||
)
var result = collection
.AsQueryable<YourClass>()
.Where(x => x.Age == 65 || x.Age == "65")
.ToList();
Using $in
(.In()
)
var result = collection
.AsQueryable<YourClass>()
.Where(x => x.age.In(new[] { 65, "65" }))
.ToList();
Or something like this (according to this question)
Using $or
:
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("age", 65) | builder.Eq("age", "65");
db.collection.Find(filter).ToList();
Using $in
:
var builder = Builders<BsonDocument>.Filter;
var filter = builder.In("age", new object[] { 65, "65" });
db.collection.Find(filter).ToList();
Upvotes: 0