Reputation: 9278
I have User object:
{
"_id" : ObjectId("599e670f2720317af451db9e"),
"Cars" : [
{
"Name" : "Car 1",
"Labels" : [
{
"Label" : "Main",
"Color" : "#F49973"
}
]
},
{
"Name" : "Car 2",
"Labels" : [
{
"Label" : "Main",
"Color" : "#F49973"
},
{
"Label" : "Secondary",
"Color" : "#E2E2E2"
}
]
}
]
}
I want to find document by user id and car name, then select this car. I am trying to do this:
await _collection.AsQueryable().Where(u => u.Id == someId && u.Cars.Any(s => s.Name == someName))
.Select(u => u.Cars[-1])
.SingleOrDefaultAsync();
In result, I want to get single Car
object, but, I get null
. How to properly to do it?
Upvotes: 1
Views: 1754
Reputation: 14436
Try this
var mongoClient = new MongoClient();
var collection = mongoClient.GetDatabase("test").GetCollection<Rootobject>("test");
ObjectId someId = new ObjectId("599e670f2720317af451db9e");
string someName = "Car 1";
var item = await collection.AsQueryable()
.Where(x => x.Id == someId)
.SelectMany(x => x.Cars)
.Where(x => x.Name == someName)
.FirstOrDefaultAsync();
This generates the below aggregation query:
{aggregate([{ "$match" : { "_id" : ObjectId("599e670f2720317af451db9e") } }, { "$unwind" : "$Cars" }, { "$project" : { "Cars" : "$Cars", "_id" : 0 } }, { "$match" : { "Cars.Name" : "Car 1" } }])}
which spits out the following results:
{ "Cars" : { "Name" : "Car 1", "Labels" : [ { "Label" : "Main", "Color" : "#F49973" } ] } }
Upvotes: 3