1

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?

0

1 Answer 1

3

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" } ] } }
Sign up to request clarification or add additional context in comments.

3 Comments

It works. Thank you. I tried almost the same query, but x.Name == someName I had in the first Where like: x.Cars.Any( c.Name == someName) and it didn't work properly.
I find that using Linq with MongoDB can sometimes complicate things, might be worth having a look at the query builder within mongo. :-)
Actually, 90% of my queries are written with help of Builders class, but I think LINQ query is more consice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.