我在 mongo db 中有一个像这样的集合
{
buckets: {
"1-10": {
base: 10,
cutoff: 100
},
"11-20": {
base: 20,
cutoff: 200
}
}
}
我想编写一个查询,以便可以轻松访问存储桶。
db.collection.aggregate([
{
$addFields: {
bucket_value: {
$switch: {
branches: [
{
case: {
$and: [
{ $gt: [{ computedBucketValue }, 0] },
{ $lt: [{ $literal: 10 }, 51] },
],
},
then: {
$ifNull: ["$buckets.1-10.base", "First bucket"],
},
},
],
default: null,
},
},
},
},
{
$project: {
bucket_value: "$bucket_value",
_id: 0,
},
},
])
computedBucketValue
已计算,并且该字段在集合中不直接可用。有人可以帮助我如何使用外部变量代替字段键。这个查询只是一个简单的查询。有很多桶,我在 js 中准备这些条件,然后再将其发送到聚合查询。
在 MongoDB 聚合中,如果您想使用由外部变量(在您的例子中为“compulatedBucketValue”)确定的字段键,您可以使用 $objectToArray 和 $filter 运算符来实现。以下是如何修改聚合查询以使用外部变量动态访问存储桶:
var computedBucketValue = 25; // External variable
db.collection.aggregate([
{
$project: {
bucket_value: {
$arrayElemAt: [
{
$map: {
input: {
$filter: {
input: { $objectToArray: "$buckets" },
as: "bucket",
cond: {
$and: [
{ $gt: [computedBucketValue, "$$bucket.v.base"] },
{ $lte: [computedBucketValue, "$$bucket.v.cutoff"] },
],
},
},
},
as: "matchedBucket",
in: "$$matchedBucket.k", // Extract the key of the matched bucket
},
},
0
],
},
_id: 0,
},
}
]);