MongoDB仅使用C#从文档中检索匹配的子文档

编程入门 行业动态 更新时间:2024-10-21 03:45:38
本文介绍了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#从文档中检索匹配的子文档

本文发布于:2023-11-22 20:39:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618936.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!