如何跨 collection 导出?
How to export across collection?
我想跨 collection 导出信息。例如,我有 2 collection User 和 Orders。用户包含登录信息(用户名),订单包含订单 ID。所以当客户购买东西时,orderID 将在 Orders collection 中生成,并且他们的 userID(与用户名不同)将记录在订单中。所以我必须引用用户 ID 才能在 User collection.
中找到用户名
我想将订单 ID 与用户名一起导出。那可能吗?目前,mongodb 指南针只有在您选择 collection.
时才会有导出按钮
您可以使用 lookup 运算符来获取用户名和订单 ID。
MongoDB Official Documentation for lookup operator
比如你的用户集合是这样的
用户合集
[{
_id:123,
username:example,
}]
订单收集
[{
_id:234
userId : ObjectId('123')
orderPrice : 300
}]
所以你可以像这样使用 $lookup
在用户对象中获取订单
db.orders.aggregate([
{
'$lookup': {
'from': 'users', // users collection
'localField': 'userId',
'foreignField': '_id',
'as': 'order'
}
])
我想跨 collection 导出信息。例如,我有 2 collection User 和 Orders。用户包含登录信息(用户名),订单包含订单 ID。所以当客户购买东西时,orderID 将在 Orders collection 中生成,并且他们的 userID(与用户名不同)将记录在订单中。所以我必须引用用户 ID 才能在 User collection.
中找到用户名我想将订单 ID 与用户名一起导出。那可能吗?目前,mongodb 指南针只有在您选择 collection.
时才会有导出按钮您可以使用 lookup 运算符来获取用户名和订单 ID。
MongoDB Official Documentation for lookup operator
比如你的用户集合是这样的 用户合集
[{
_id:123,
username:example,
}]
订单收集
[{
_id:234
userId : ObjectId('123')
orderPrice : 300
}]
所以你可以像这样使用 $lookup
在用户对象中获取订单db.orders.aggregate([
{
'$lookup': {
'from': 'users', // users collection
'localField': 'userId',
'foreignField': '_id',
'as': 'order'
}
])