从文档中的不同结构展开多个数组

2024-04-19 00:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的收藏中有两种结构:

{
    _id: "date1",
    users: [{"user": "123", ...}, {"user": "456", ...}]
}

以及

{
    _id: "date2",
    points: [{"point": "1234", ...}, {"point": "5678", ...}]
}

我需要做一个agregation,它返回给我这些文件的列表,只有特定的点或用户信息,并带有skip和limit。比如:

[
    {_id: "date1", user: {"user": "123", ...}},
    {_id: "date2", point: {"point": "1234", ...}},
]

我用过,我是蒙哥人,你能给我推荐吗?你知道吗

collection.aggregate([
{"$unwind": "$users"},
{"$unwind": "$points"},
{"$match": {"$or": [
    {'users.user': an_user},
    {'points.point': a_point}]}},
{"$sort": {"_id": -1}},
{"$skip": 10},
{"$limit": 10}
])

Tags: 文件用户id列表结构userspointspoint
1条回答
网友
1楼 · 发布于 2024-04-19 00:28:48

with the information of one specific user or one specific point depending if point or user key is in that document

根据您提供的文档示例,您可以仅使用db.collection.find(),例如:

db.collection.find({"users.user": a_user}, {"users.$":1});
db.collection.find({"points.point": a_point}, {"points.$":1});

根据您的用例,这可能并不理想,因为您要执行find()两次。 这将返回一个带有_id的文档列表。上述查询相当于说:

Find all documents in the collection 
where in array field users contain a user 'a_user' 
OR in array field points contain a point 'a_point'

另见MongoDB Indexes

说到上面,你应该重新考虑你的文档模式。根据您的用例,您可能会在以后查询数据时遇到困难,并且可能会影响查询性能。请查看MongoDB Data Models以提供有关如何设计模式的更多信息。你知道吗

相关问题 更多 >