简体   繁体   English

MongoDB:如何查询集合的所有子文档

[英]MongoDB: How to query all subdocuments of a collection

I have the collection users , and each of the user objects have a field called purchases which is an array of objects. 我有集合users ,每个用户对象都有一个称为purchases的字段,它是对象的数组。 The user object looks as follows: 用户对象如下所示:

User:
{
    ...
    purchases: [
        { time: 2355645366, amount: 2000 },
        { time: 2456456334, amount: 2000 },
        { time: 2435645433, amount: 2000 },
    ]
}

How do I query for all purchases among all users, as well as sort by fields such as time ? 如何查询所有用户之间的所有购买交易以及如何按time例如time字段进行排序? The result I would expect would be an array of purchase objects. 我期望的结果将是购买对象的数组。

You can use aggregations operations, a very handy tool for scenarios like this 您可以使用聚合操作,这对于这种情况非常方便

db.users.aggregate({$unwind: '$purchases'},{$sort: {'purchases.time': 1}},{$group: {_id: 0, 'purchases': {$push: '$purchases'}}})

the returned document will have the following structure : 返回的文档将具有以下结构:

{ "_id" : 0, "purchases" : [...all users purchases sorted by time here...]}

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

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