如何获取在另一个集合中引用的 MongoDB 文档的列表
How do I get a list of MongoDB documents that are referenced inside another collection
我正在尝试找到一种方法来获取在另一个集合的子文档中引用的 MongoDB 个文档的列表。
我收集了一些用户文档。在另一个集合中,我保留了一份企业清单。每个企业都有一个子文档,其中包含对用户的引用列表。
用户合集:
/* user-1 */
{
"_id" : ObjectId("54e5e78680c7e191218b49b0"),
"username" : "jachim@example.com",
"password" "yp6hx3sd200cko4o0w04u46jNv3tNl3qpVWVbnAyzZpDxsSVDDLS"
}
/* user-2 */
{
"_id" : ObjectId("54e5e78480c7e191218b49ab"),
"username" : "jachim@example.net",
"password" : "y7amk1a7fwo4sgw8kkkcuWi4vhj2zKvZZIEDWtDQLo6dUjb0YnYy",
}
商务合集
/* business-1 */
{
"_id" : ObjectId("54e5e78880c7e191218b4c52"),
"name" : "Stack Overflow",
"users" : [
{
"$ref" : "User",
"$id" : ObjectId("54e5e78680c7e191218b49b0"),
"$db" : "test"
}
]
}
我可以按照 business.users 列表中的引用从企业获取用户,我可以使用 db.Business.find({"users.$id": ObjectId("54e5e78480c7e191218b49ab")})
查询从用户获取企业,但是 我无法创建查询来查找业务中某处引用的所有用户。
我可以分两步完成此客户端:
db.Business.distinct("users.$id");
这将 return 用户 ID 列表。我可以在查询用户集合时使用此列表:
db.User.find({ _id: { $in: [ LIST_OF_IDS ] } });
但这可能会导致非常大的查询(可能导致查询大于 16MB)。
我认为 MapReduce 可以解决这个问题,但我不太确定我应该在那里使用哪些字段。
这里有这方面的专家吗?
经过更多研究并在 MongoDB IRC 频道聊天后,有几个选项可以使它起作用:
- 使用
$in
查询。
- 跟踪双方的关系(保持双方关系的最新状态有点困难,但它有效)。
- 更改关系的拥有方(在用户文档中跟踪业务),但这取决于您的查询的性质。
Aggregation Framework would not work, because it cannot query multiple collections, nor will MapReduce (for the same reason, although it is possible).
我正在尝试找到一种方法来获取在另一个集合的子文档中引用的 MongoDB 个文档的列表。
我收集了一些用户文档。在另一个集合中,我保留了一份企业清单。每个企业都有一个子文档,其中包含对用户的引用列表。
用户合集:
/* user-1 */
{
"_id" : ObjectId("54e5e78680c7e191218b49b0"),
"username" : "jachim@example.com",
"password" "yp6hx3sd200cko4o0w04u46jNv3tNl3qpVWVbnAyzZpDxsSVDDLS"
}
/* user-2 */
{
"_id" : ObjectId("54e5e78480c7e191218b49ab"),
"username" : "jachim@example.net",
"password" : "y7amk1a7fwo4sgw8kkkcuWi4vhj2zKvZZIEDWtDQLo6dUjb0YnYy",
}
商务合集
/* business-1 */
{
"_id" : ObjectId("54e5e78880c7e191218b4c52"),
"name" : "Stack Overflow",
"users" : [
{
"$ref" : "User",
"$id" : ObjectId("54e5e78680c7e191218b49b0"),
"$db" : "test"
}
]
}
我可以按照 business.users 列表中的引用从企业获取用户,我可以使用 db.Business.find({"users.$id": ObjectId("54e5e78480c7e191218b49ab")})
查询从用户获取企业,但是 我无法创建查询来查找业务中某处引用的所有用户。
我可以分两步完成此客户端:
db.Business.distinct("users.$id");
这将 return 用户 ID 列表。我可以在查询用户集合时使用此列表:
db.User.find({ _id: { $in: [ LIST_OF_IDS ] } });
但这可能会导致非常大的查询(可能导致查询大于 16MB)。
我认为 MapReduce 可以解决这个问题,但我不太确定我应该在那里使用哪些字段。
这里有这方面的专家吗?
经过更多研究并在 MongoDB IRC 频道聊天后,有几个选项可以使它起作用:
- 使用
$in
查询。 - 跟踪双方的关系(保持双方关系的最新状态有点困难,但它有效)。
- 更改关系的拥有方(在用户文档中跟踪业务),但这取决于您的查询的性质。
Aggregation Framework would not work, because it cannot query multiple collections, nor will MapReduce (for the same reason, although it is possible).