假设我们有这个ID数组,它包含重复的值。
[
'A',
'B',
'C',
'C',
'C',
'D',
.
.
.
]如何从DB中为每个ID选择匹配?我不需要独特的排行。我的意思是结果数组必须包含三个相同的行,用于ID C。一对一的指点。谢谢。
发布于 2022-01-27 00:55:59
最好是在客户端这样做,因为您可能只需在服务器上创建大量重复的数据并返回到客户端。
db.collection.aggregate([
{
"$match": {
_id: {
"$in": [ "A", "B", "C", "C", "C", "D" ]
}
}
},
{
"$group": {
"_id": null,
"fields": {
"$push": "$$ROOT"
}
}
},
{
"$set": {
"fields": {
"$map": {
"input": [ "A", "B", "C", "C", "C", "D" ],
"as": "id",
"in": {
$let: {
vars: {
"findOne": {
"$first": {
"$filter": {
"input": "$fields",
"as": "item",
"cond": {
"$eq": [ "$$item._id", "$$id" ]
}
}
}
}
},
in: {
"$cond": {
"if": "$$findOne",
"then": "$$findOne",
"else": { _id: "$$id" }
}
}
}
}
}
}
}
},
{
"$unwind": "$fields"
},
{
"$replaceRoot": { "newRoot": "$fields" }
}
])https://stackoverflow.com/questions/70870691
复制相似问题