我在mongo中有以下文档
{"_id":{"$oid":"5e7b6cb9606503483494c63a"},"ProductId":{"$binary":{"base64":"V9+9bOaj8kyWrPwdAm0rBQ==","subType":"03"}},"ProductName":"TestProduct1","ProductItems":[{"_t":"ProductItem","ProductId":{"$binary":{"base64":"V9+9bOaj8kyWrPwdAm0rBQ==","subType":"03"}},"Code":"TP1A"},
{"_t":"ProductItem","ProductId":{"$binary":{"base64":"V9+9bOaj8kyWrPwdAm0rDE==","subType":"03"}},"Code":"TP1B"}]}
我想做的是通过对ProductItem.Code的查询返回,该查询返回具有单个匹配子项的产品。因此,保留了对象结构,但消除了除单个匹配子对象之外的所有子对象。
我尝试过
Product prod = new Product();
IMongoCollection<Product> products = _database.GetCollection<Product>("Products");
var filter = Builders<Product>.Filter.ElemMatch(x=>x.ProductItems, x=>x.Code==code);
prod = products.Find(filter).FirstOrDefault();
return prod;
但这最终会返回根文档和所有子文档,而不是返回我搜索的根文档和单个子文档。
答案 0 :(得分:0)
您可以使用位置运算符将匹配的文档投影到数组中。这是C#(https://docs.mongodb.com/manual/reference/operator/projection/positional/)中的[-1]
var filter = Builders<Product>.Filter.ElemMatch(x=>x.ProductItems, x=>x.Code==code);
var projection = Builders< Product >.Projection.Include(x => x.ProjectItems[-1])
var found = await collection.Find(filter, projection).ToListAsync();
var matchedProductItem = found[0].ProductItems.First();