Mongodb管道与先前查找的项匹配

3phpmpom  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(317)

我有一个mongodb查询做管道查找和结果存储为一个新的数组下的关键字“A”,我找不到一个例子,如何添加另一个管道注入另一个查找下的关键字“B”,但使用匹配字段从第一个查找。类似于选择所有文档从集合根,添加文档从集合A,其中A.id = ROOT.id作为数组A,并添加文档从集合B,其中A.x=B.x作为数组A.B
具有所需输出的集合示例:

  1. ROOT {"_id":1,"type":"customer","name":"anton"}
  2. A {"_id":33, "customer":1, "type":"order","address":"azores island"}
  3. B {"_id":"1_33_1", "type":"item","name":"golf ball"}
  4. and want to achieve this output. the id incollection B is in the format of customerId_orderId_itemIndex, a string join
  5. {"_id":1,"type":"customer","name":"anton",
  6. "orders": [
  7. {
  8. "_id":33, "customer":1, "type":"order","address":"azores island",
  9. "items":[{"_id":"33_1", "type":"item","name":"golf ball"}]
  10. }
  11. ]}

字符串

wlsrxk51

wlsrxk511#

集合B中的id的格式为customerId_orderId_itemIndex,一个字符串连接
这使得连接数据的工作变得更加复杂。与此相关的是,我并不清楚为什么要将信息存储在集合B中,而不是将它们嵌入到数组中。我个人强烈建议至少考虑一下,因为它可以大大简化当前和未来的开发。
然而,你可以通过以下类似的方法来实现你问题中所述的目标:

  1. db.ROOT.aggregate([
  2. {
  3. "$lookup": {
  4. "from": "A",
  5. "localField": "_id",
  6. "foreignField": "customer",
  7. "as": "orders",
  8. pipeline: [
  9. {
  10. "$lookup": {
  11. "from": "B",
  12. let: {
  13. regex: {
  14. "$concat": [
  15. "^",
  16. {
  17. $toString: "$customer"
  18. },
  19. "_",
  20. {
  21. "$toString": "$_id"
  22. }
  23. ]
  24. }
  25. },
  26. pipeline: [
  27. {
  28. $match: {
  29. $expr: {
  30. $regexMatch: {
  31. input: "$_id",
  32. regex: "$$regex"
  33. }
  34. }
  35. }
  36. }
  37. ],
  38. "as": "items"
  39. }
  40. }
  41. ]
  42. }
  43. }
  44. ])

字符串
在这里,我们:
1.在ROOTA之间执行(简单)$lookup,以获取相关的orders文档。

  • 嵌套在该操作中,我们在AB之间执行另一个$lookup,以获取相关的items文档。
  • 值得注意的是,在这里我们必须跳过一些环来构造一个正则表达式模式,当匹配B中文档的_id字段时,我们可以使用它。

使用以下示例数据:

  1. "ROOT": [
  2. {
  3. "_id": 1,
  4. "type": "customer",
  5. "name": "anton"
  6. }
  7. ],
  8. "A": [
  9. {
  10. "_id": 33,
  11. "customer": 1,
  12. "type": "order",
  13. "address": "azores island"
  14. }
  15. ],
  16. "B": [
  17. {
  18. "_id": "1_33_1",
  19. "type": "item",
  20. "name": "golf ball"
  21. },
  22. {
  23. "_id": "1_33_2",
  24. "type": "item",
  25. "name": "golf club"
  26. },
  27. {
  28. "_id": "2_33_1",
  29. "type": "item",
  30. "name": "golf ball"
  31. }
  32. ]


输出为:

  1. [
  2. {
  3. "_id": 1,
  4. "name": "anton",
  5. "orders": [
  6. {
  7. "_id": 33,
  8. "address": "azores island",
  9. "customer": 1,
  10. "items": [
  11. {
  12. "_id": "1_33_2",
  13. "name": "golf club",
  14. "type": "item"
  15. },
  16. {
  17. "_id": "1_33_1",
  18. "name": "golf ball",
  19. "type": "item"
  20. }
  21. ],
  22. "type": "order"
  23. }
  24. ],
  25. "type": "customer"
  26. }
  27. ]


了解它在this playground example中的工作原理

展开查看全部

相关问题