返回所有字段MongoDB Aggregate [英] Return all fields MongoDB Aggregate

查看:617
本文介绍了返回所有字段MongoDB Aggregate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在这里搜索,但找不到真正需要的东西.我有这样的文件:

I tried searching on here but couldn't really find what I need. I have documents like this:

{
    appletype:Granny,
    color:Green,
    datePicked:2015-01-26,
    dateRipe:2015-01-24,
    numPicked:3
},

{
    appletype:Granny,
    color:Green,
    datePicked:2015-01-01,
    dateRipe:2014-12-28,
    numPicked:6
}

我只想退回所有田间最新采摘的苹果.我希望查询仅本质上返回第一份文档.当我尝试做时:

I would like to return only those apples picked latest, will all fields. I want my query to return me the first document only essentially. When I try to do:

db.collection.aggregate([
    { $match : { "appletype" : "Granny" } },
    { $sort : { "datePicked" : 1 } },
    { $group : { "_id" : { "appletype" : "$appletype" },
        "datePicked" : { $max : "$datePicked" } },
])

它确实返回了我所有最近采摘的苹果,但是只有appletype:Granny和datePicked:2015-01-26.我需要其余字段.我尝试使用$ project并添加所有字段,但是并没有得到我所需要的东西.另外,当我将其他字段添加到组中时,由于datePicked是唯一的,因此它返回了两条记录.

It does return me all the apples picked latest, however with only appletype:Granny and datePicked:2015-01-26. I need the remaining fields. I tries using $project and adding all the fields, but it didn't get me what I needed. Also, when I added the other fields to the group, since datePicked is unique, it returned both records.

如何只返回最新的datePicked返回所有字段?

How can I go about returning all fields, for only the latest datePicked?

谢谢!

推荐答案

从您的描述中看来,您希望为集合中每种苹果类型创建一个文档,并显示具有最新datePicked值的文档

From your description, it sounds like you want one document for each of the types of apple in your collection and showing the document with the most recent datePicked value.

以下是该查询的汇总查询:

Here is an aggregate query for that:

db.collection.aggregate([
  { $sort: { "datePicked": -1 },
  { $group: { _id: "$appletype", color: { $first: "$color" }, datePicked: { $first: "$datePicked" }, dateRipe: { $first: "$dateRipe" }, numPicked: { $first: "$numPicked" } } },
  { $project: { _id: 0, color: 1, datePicked: 1, dateRipe: 1, numPicked: 1, appletype: "$_id" } }
])

但是根据您编写的汇总查询,您似乎正在尝试获取该信息:

But then based on the aggregate query you've written, it looks like you're trying to get this:

db.collection.find({appletype: "Granny"}).sort({datePicked: -1}).limit(1);

这篇关于返回所有字段MongoDB Aggregate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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