我有三个文档。第一个是百分比,其他是丢弃的项目和过滤的项目。这些文件的示例数据如下。
db = {
"percentages": [
{
"_id": 1,
"base": "A",
"buy": "BUY_1",
"sell": "SELL_1",
"item": "ITEM_B",
"ask": 100,
"bid": 114,
"percentage": 14
},
{
"_id": 2,
"base": "B",
"buy": "BUY_2",
"sell": "SELL_2",
"item": "ITEM_G",
"ask": 50,
"bid": 90,
"percentage": 80
},
{
"_id": 3,
"base": "A",
"buy": "BUY_2",
"sell": "SELL_2",
"item": "ITEM_G",
"ask": 10,
"bid": 15,
"percentage": 50
}
],
"discardeditems": [
{
"_id": 1,
"buy": "BUY_1",
"sell": "SELL_1",
"item": "ITEM_B"
},
{
"_id": 2,
"buy": "BUY_2",
"sell": "SELL_2",
"item": "ITEM_G"
}
],
"filtereditems": [
{
"_id": 2,
"buy": "BUY_2",
"sell": "SELL_2",
"item": "ITEM_G",
"percentage": "55"
}
]
}
实际上,我想将百分比文档与丢弃的项目和过滤的项目文档进行比较。如果百分比文档中的买入、卖出和项目值等于丢弃物品文档中的值,我想在百分比文档中添加isdiscardeditem:true
。
如果过滤项目中的买入、卖出和项目值等于百分比文档中的值,并且过滤项目文档中的百分比值大于百分比文档中的值,我不想再显示此记录。
我想看的数据的最终版本应该如下;
{
"_id": 1,
"base": "A",
"buy": "BUY_1",
"sell": "SELL_1",
"item": "ITEM_B",
"ask": 100,
"bid": 114,
"percentage": 14,
"isdiscarded": true
},
{
"_id": 2,
"base": "B",
"buy": "BUY_2",
"sell": "SELL_2",
"item": "ITEM_G",
"ask": 50,
"bid": 90,
"percentage": 80,
"isdiscarded": true
}
百分比文档计数为3。但现在我想展示两个记录。其他百分比记录文档不得因为小于筛选项中的百分比而出现。
我可以使用$lookup, $match $addFields
关键字添加 isdisdecardeditem,但我没有成功显示两条记录。 https://mongoplayground.net/p/_XZoqGTnIyz
怎么写?
您可以尝试以下聚合:
db.percentages.aggregate([
{
$lookup: {
from: "discardeditems",
let: {
item_src: "$item",
buy_src: "$buy",
sell_src: "$sell"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: [ "$$item_src", "$item" ] },
{ $eq: [ "$$buy_src", "$buy" ] },
{ $eq: [ "$$sell_src", "$sell" ] },
]
}
}
}
],
as: "discarded"
}
},
{
$lookup: {
from: "filtereditems",
let: {
item_src: "$item",
buy_src: "$buy",
sell_src: "$sell",
percentage_src: "$percentage"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: [ "$$item_src", "$item" ] },
{ $eq: [ "$$buy_src", "$buy" ] },
{ $eq: [ "$$sell_src", "$sell" ] },
{ $lt: [ "$$percentage_src", { $toInt: "$percentage" } ] }
]
}
}
}
],
as: "filtered"
}
},
{
$match: {
filtered: { $eq: [] }
}
},
{
$addFields: {
isdiscarded: { $gt: [ { $size: "$discarded" }, 0 ] }
}
},
{
$project: {
discarded: 0,
filtered: 0
}
}
])
请注意,percentage
字段必须具有相同的类型,因此转换需要$toInt。
蒙戈游乐场