如何在MongoDB中按$ elemMatch排序? [英] How can I sort by $elemMatch in MongoDB?

查看:95
本文介绍了如何在MongoDB中按$ elemMatch排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MongoDB数据库中,我有一系列产品.每个产品都以数组形式包含发布信息,例如

In my MongoDB database I have a collection of products. Each product contains release information in an array, e.g.

{
  "name" : "foo",
  "release" : [{
      "region" : "GB",
      "active" : "Y",
      "date" : ISODate("2012-03-01T00:00:00Z")
    }, {
      "region" : "US",
      "active" : "Y",
      "date" : ISODate("2012-09-01T00:00:00Z")
    }, {
      "region" : "FR",
      "active" : "N",
      "date" : ISODate("2010-01-01T00:00:00Z")
    }]
}

我想找到GB区域中处于活动发行状态的所有产品,然后按GB发行日期对结果进行排序.

I want to find all products that are on active release in the GB region, and sort the results by the GB release date.

我尝试使用:

db.product.find(
  { "release" : { "$elemMatch" : { "region" : "GB", "active" : "Y" } } }
).sort({ "release.date" : 1 });

这会找到正确的产品,但不会按匹配元素的发布日期排序(而是按数组中的最小发布日期排序).

This finds the correct products, but does not sort by the release date from the matched element (instead it sorts on the minimum release date from the array).

到目前为止,我似乎无法对匹配元素的属性进行排序,对吗?

From what I have read so far, it looks like sorting by properties of the matched element is not possible, is this correct?

可以使用聚合框架完成吗? /p>

Can it be done with the aggregation framework, and if so how?

推荐答案

以下是您可以运行以获取所需内容的汇总:

Here is the aggregation you could run to get what you want:

db.release.aggregate([
         {$unwind:"$release"},
         {$match:{"release.active":"Y", "release.region":"GB"}},
         {$sort:{"release.date":1}}
])

这将展开发布数组,根据您的条件匹配文档,并在发布日期对选定的文档进行排序.

This unwinds the release array, matches the documents by your criteria and sorts selected ones on release date.

这篇关于如何在MongoDB中按$ elemMatch排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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