所以我的 MongoDb 文档看起来像这样:
{
"_id" : ObjectId("5f1842d238ec58056d94bbb3"),
"itemsPurchased" : [
{
"_id" : "5e7365360665d10011756af2",
"created" : "2020-03-19T12:27:34.108Z",
"productLine" : "5ce8ec9df5cc72002fee0d4e",
"price" : 1.9,
"tax" : 7,
"ean" : "42272120",
"expirationDate" : "2020-06-17T12:27:34.103Z",
"kiosk" : "5c17a3d963ca649138ec522c",
"loadCell" : "1"
},
{
"_id" : "5e7365360665d10011756af3",
"created" : "2020-03-19T12:27:34.108Z",
"productLine" : "5ce8ec9df5cc72002fee0d4e",
"price" : 1.9,
"tax" : 7,
"ean" : "42272120",
"expirationDate" : "2020-06-17T12:27:34.103Z",
"kiosk" : "5c17a3d963ca649138ec522c",
"loadCell" : "1"
}
],
"paymentMethod" : [],
"type" : "purchase",
"total" : NumberDecimal("3.8"),
"session" : ObjectId("5f1842bf1f2028e369d945f0"),
"orgId" : ObjectId("5cddce9a51cbb2002d636741"),
"created" : ISODate("2020-07-22T13:44:50.973Z"),
"updated" : ISODate("2020-07-22T13:44:50.973Z"),
"__v" : 0
}
问题是 itemsPurchased[] 内部(由于逻辑错误)有字符串类型的 id。这里以"_id" : "5e7365360665d10011756af2"
和为例"productLine" : "5ce8ec9df5cc72002fee0d4e"
。如何浏览所有在 itemsPurchased[] 中具有字符串而不是 ObjectIds 的对象的文档,并将它们转换为 ObjectId 类型。我尝试将 $convert 和 $toObjectId 与 $map 一起使用,但似乎无法正确使用。
db.transactions.aggregate([
{ "$match": { "itemsPurchased._id": {$type: "string"}}},
{ "$set": "itemsPurchased1": {
"$map": {
"input": "$itemsPurchased",
"in": {
"$toObjectId": [
"$$this",
{
"productLine": {
"$toObjectId": "$$this.productLine"
}
}
]
}
}
}
}
无法正确获取地图部分