sql >> Base de Datos >  >> NoSQL >> MongoDB

C# Mongodb. Encuentre el elemento en la matriz y seleccione solo este elemento

Prueba esto

        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();

Esto genera la siguiente consulta de agregación:

{aggregate([{ "$match" : { "_id" : ObjectId("599e670f2720317af451db9e") } }, { "$unwind" : "$Cars" }, { "$project" : { "Cars" : "$Cars", "_id" : 0 } }, { "$match" : { "Cars.Name" : "Car 1" } }])}

que arroja los siguientes resultados:

{ "Cars" : { "Name" : "Car 1", "Labels" : [ { "Label" : "Main", "Color" : "#F49973" } ] } }