简体   繁体   English

如何在mongodb中为X用户找到嵌入在数组中的最新字段

[英]How to find the most current field that is embedded in an array for X user in mongodb

I need to find a user with X _id and I need the most current weightTracker.date usually it will be the last one. 我需要找到一个具有X _id的用户,并且我需要最新的weightTracker.date通常是最后一个。

I've tried db.user.find({_id:userid}, {weightTracker:1}).sort({"weightTracker.date":-1}) With little success on ordering my results. 我已经尝试过db.user.find({_id:userid}, {weightTracker:1}).sort({"weightTracker.date":-1})对我的结果排序几乎没有成功。 But most important that always returns all the results and I am only interested in the most current one . 但是最重要的是总是返回所有结果, 我只对最新的结果感兴趣

How Could I get the most recent object in weightTracker given the object's date in user X? 给定用户X中的date ,如何在weightTracker获取最新的对象?

User 用户

_id
weightTracker[{ manyproperties:menyproperties, date:date}]

在此处输入图片说明

You might want to try aggregate method (for detailed examples, you can see http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/ ) 您可能想尝试使用汇总方法(有关详细示例,请参见http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/

db.user.aggregate( { $match: { "_id": ObjectId("52426846311fc102641ef332") } } , 
                   { $unwind: "$weightTracker"},  
                   {$group: { _id: null, maxDate: {$max: "$weightTracker" } } }  
                 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM