簡體   English   中英

查找字段中最新的所有文檔,並且與mongodb集合中的另一個字段不同

[英]find all the documents that is the latest by a field and distinct by another field in mongodb collection

我想將整個文檔提取到組中。

舉個例子,我有一個名為“sub_comment”的集合。

每個“sub_comment”都將“comment”中的一個引用為“commentId”。

sub_comment = new Schema({  // as per mongoose schema
   updatedAt : Date,
   text : String,
   by : String,
   info : String,
   commentId : { type : ObjectId, ref : 'commment' }
})

現在我想提取所有那些最新的子語句(完整文檔)(通過“updatedAt”)按每個注釋分組。

我目前正在這樣做:

mongoose.model('sub_comment').aggregate([
            { $sort: { commentId : 1, updatedAt: -1 } },
            { $group: { _id: "$commentId", updatedAt: { $first: "$updatedAt" } } }
          ]

當然,這只返回updatedAtcommentId這兩個字段。

現在如果我想要整個文件怎么辦? 我將不得不分別寫每個字段,我不想這樣做。

什么應該是首選方法?

編輯:簡單的查詢

集合=

[
{commentId : 1, updatedAt : ISO("2015-10-13T11:38:29.000Z"), xyz  : 'xyz1' },
{commentId : 2, updatedAt : ISO("2015-10-10T11:38:29.000Z"), xyz  : 'xyz2'  },
{commentId : 2, updatedAt : ISO("2015-10-14T11:38:29.000Z"), xyz  : 'xyz3'  },
{commentId : 1, updatedAt : ISO("2015-10-11T11:38:29.000Z"), xyz  : 'xyz4'  }
]

我想要輸出:

[
{commentId : 1, updatedAt : ISO("2015-10-13T11:38:29.000Z"), 'xyz' : 'xyz1' },
{commentId : 2, updatedAt : ISO("2015-10-14T11:38:29.000Z"), 'xyz' : 'xyz3'  }
]

您可以在聚合中使用$$ROOT系統變量來引用管道中該階段的完整頂級文檔:

mongoose.model('sub_comment').aggregate([
        { $sort: { commentId : 1, updatedAt: -1 } },
        { $group: { _id: "$commentId", doc: { $first: "$$ROOT" } } }
      ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM