C#Mongodb。在数组中查找项目并仅选择此项目

时间:2017-09-29 10:57:22

标签: c# mongodb

我有用户对象:

{ 
    "_id" : ObjectId("599e670f2720317af451db9e"),
    "Cars" : [
        {
            "Name" : "Car 1",
            "Labels" : [
                {
                    "Label" : "Main", 
                    "Color" : "#F49973"
                }
            ]
        }, 
        {
            "Name" : "Car 2",               
            "Labels" : [    
                {
                    "Label" : "Main", 
                    "Color" : "#F49973"
                },
                {
                    "Label" : "Secondary", 
                    "Color" : "#E2E2E2"
                }

            ]
        }
    ]
}

我想按用户ID和车名找到文件,然后选择这辆车。我想这样做:

 await _collection.AsQueryable().Where(u => u.Id == someId && u.Cars.Any(s => s.Name == someName))
                .Select(u => u.Cars[-1])
                .SingleOrDefaultAsync();

结果,我想获得单个Car对象,但是,我得到null。如何正确地做到这一点?

1 个答案:

答案 0 :(得分:3)

试试这个

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

这将生成以下聚合查询:

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

吐出以下结果:

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