MongoDB仅使用C#从文档中检索匹配的子文档 [英] MongoDB retrieve only matching sub documents from a document with c#

查看:225
本文介绍了MongoDB仅使用C#从文档中检索匹配的子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望下面的查询仅返回 empActivity 数组中的子文档,其中每个子文档中的 Stamp 字段均与 Stamp 查询中的值. empId empActivity empActivity 具有嵌入文档的外部级别字段.

I want the following query below to only return those sub documents from the empActivity array where the Stamp field in every sub document matches the Stamp value in the query. empId and empActivity are the outer level fields with empActivity having embedded documents.

db.emp_activity.find({$and : [{"empId" : "999"}, {"empActivity.Stamp" : { $lte : ISODate("2015-01-09T12:33:39.927Z")}}]})

问题在于,它还会返回所有与查询中的日期不匹配的子文档,除了日期为2015年1月9日的4个子文档之外,上面的查询还会返回日期大于9th的子文档2015年1月.

The problem is that it also returns all the sub documents that dont match the date in the query, apart from the 4 sub documents having a date of 9th Jan 2015, the query above also returns sub documents whose date is greater than 9th Jan, 2015.

推荐答案

所需的输出可以通过聚合来产生:

The desired output could be produce just by aggregation:

db.collection.aggregate([
   {$match : { empId : '999', 'empActivity.Stamp' : { $lte : ISODate("2015-01-09T12:33:39.927Z")} }},
   {$unwind : '$empActivity'},
   {$match : { empId : '999', 'empActivity.Stamp' : { $lte : ISODate("2015-01-09T12:33:39.927Z")} }},
   {$group: { _id: '$empId', empActivity: { $addToSet: '$empActivity' }}}
])

在c#中:

var args = new AggregateArgs
{
    Pipeline = new List<BsonDocument>
    {
        BsonDocument.Parse("{$match : { empId : '999', 'empActivity.Stamp' : { $lte : ISODate('2015-01-09T12:33:39.927Z')} }}"),
        BsonDocument.Parse("{$unwind : '$empActivity'}"),
        BsonDocument.Parse("{$match : { empId : '999', 'empActivity.Stamp' : { $lte : ISODate('2015-01-09T12:33:39.927Z')} }}"),
        BsonDocument.Parse("{$group: { _id: '$empId', empActivity: { $addToSet: '$empActivity' }}}"),
    }
};

var result = collection.Aggregate(args).ToList();

这篇关于MongoDB仅使用C#从文档中检索匹配的子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆