在这种情况下如何获得此结果?
我有一个名为硬币的收藏
[
{
"_id" : ObjectId("5dc8c47f638267be1b00e808"),
"mintTxid" : "abc371bb13034ed6acf96a39e09b22347f0038002eb8a21493032885ba6b77da",
"address" : "mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow",
"spentTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46"
},
{
"_id" : ObjectId("5dc91d0d638267be1b21c2eb"),
"mintTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"address" : "mwE7bR8nLF9G1jUY17DzRhdWRrs4fGppvA"
}
]
我使用$ lookup并加入了自己(spentTxid = mintTxid)
db.getCollection('coins').aggregate([
{ $match: {'address': 'mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow'}},
{
$lookup: {
from: 'coins',
localField: 'spentTxid',
foreignField: 'mintTxid',
as: 'spents'
}
},
{
$unwind: {
path: '$spents',
preserveNullAndEmptyArrays: true
}
}
])
这是结果
{
"_id" : ObjectId("5dc8c47f638267be1b00e808"),
"mintTxid" : "abc371bb13034ed6acf96a39e09b22347f0038002eb8a21493032885ba6b77da",
"address" : "mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow",
"spentTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"spents" : {
"_id" : ObjectId("5dc91d0d638267be1b21c2eb"),
"mintTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"address" : "mwE7bR8nLF9G1jUY17DzRhdWRrs4fGppvA",
}
}
我如何获得这样的结果?我使用了$ replaceRoot选项,但是该选项仅返回子项。
[
{
"_id" : ObjectId("5dc8c47f638267be1b00e808"),
"mintTxid" : "abc371bb13034ed6acf96a39e09b22347f0038002eb8a21493032885ba6b77da",
"address" : "mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow",
"spentTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
},
{
"_id" : ObjectId("5dc91d0d638267be1b21c2eb"),
"mintTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"address" : "mwE7bR8nLF9G1jUY17DzRhdWRrs4fGppvA",
}
]
请帮助我...
答案 0 :(得分:0)
在聚合之后,添加以下流水线阶段,然后尝试:
{
$project: {
array: {
$concatArrays: [
[
{
_id: "$$ROOT._id",
address: "$$ROOT.address",
mintTxid: "$$ROOT.mintTxid",
spentTxid: "$$ROOT.spentTxid",
}
],
[
"$$ROOT.spents"
]
]
}
}
},
{
$unwind: "$array"
},
{
$replaceRoot: {
newRoot: "$array"
}
}