我有 3 个收藏(用户、信用和状态)。每个用户都有 1 个信用数据和许多状态数据,如下所示:
用户文档
[
{
"_id": ObjectId("669fbce1704d41e9040cbb41"),
"Name": "First User"
},
{
"_id": ObjectId("669fbce1704d41e9040cbb42"),
"Name": "Second User"
},
{
"_id": ObjectId("669fbce1704d41e9040cbb43"),
"Name": "Third User"
}
]
信用文件
[
{
"_id": ObjectId("669fbce1704d41e9040cbb44"),
"userId": ObjectId("669fbce1704d41e9040cbb41"),
"credit": 100
},
{
"_id": ObjectId("669fbce1704d41e9040cbb45"),
"userId": ObjectId("669fbce1704d41e9040cbb42"),
"credit": 10
},
{
"_id": ObjectId("669fbce1704d41e9040cbb46"),
"userId": ObjectId("669fbce1704d41e9040cbb43"),
"credit": 100
}
]
状态文件
[
{
"_id": ObjectId("669fbce1704d41e9040cbb47"),
"userId": ObjectId("669fbce1704d41e9040cbb41"),
"status": "First User Status",
"useCredit": 1
},
{
"_id": ObjectId("669fbce1704d41e9040cbb48"),
"userId": ObjectId("669fbce1704d41e9040cbb42"),
"status": "Second User Status",
"useCredit": 20
},
{
"_id": ObjectId("669fbce1704d41e9040cbb49"),
"userId": ObjectId("669fbce1704d41e9040cbb42"),
"status": "Second User Status",
"useCredit": 10
},
{
"_id": ObjectId("669fbce1704d41e9040cbb4a"),
"userId": ObjectId("669fbce1704d41e9040cbb43"),
"status": "Third User Status",
"useCredit": 3
},
{
"_id": ObjectId("669fbdac704d41e9040cbb4c"),
"userId": ObjectId("669fbce1704d41e9040cbb43"),
"status": "Third User Status",
"useCredit": 4
},
{
"_id": ObjectId("669fbdac704d41e9040cbb4d"),
"userId": ObjectId("669fbce1704d41e9040cbb43"),
"status": "Third User Status",
"useCredit": 2
},
{
"_id": ObjectId("669fbdac704d41e9040cbb50"),
"userId": ObjectId("669fbce1704d41e9040cbb43"),
"status": "Third User Status",
"useCredit": 2
}
]
我想获得随机状态:
示例:
如果第一个用户进行查询,他将从状态文档中获取一个随机数据,除了“_id:669fbce1704d41e9040cbb47”(因为自己的状态)和“_id:669fbce1704d41e9040cbb48”(因为信用不够)。
我正在考虑使用聚合,但我不知道该怎么做..
这应该达到目的
db.Status.aggregate([
{
$match: {
userId: { $ne: ObjectId("123") } // Replace "123" with the current user's _id
}
},
{
$lookup: {
from: "Credit",
localField: "userId",
foreignField: "userId",
as: "creditInfo"
}
},
{
$unwind: "$creditInfo"
},
{
$match: {
$expr: {
$gte: ["$creditInfo.credit", "$useCredit"]
}
}
},
{
$sample: { size: 1 }
}
]);