如何将带exist的sql查询转换为mongodb查询

sdnqo3pr  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(510)

我有两个关于mongodb的文件,分别是百分比和项目。我擅长sql,我可以写plsql查询如下,但我不能转换为mongodb查询。因为我的mongodb知识水平才刚刚起步。
事实上,我知道我必须使用$gt的和条件。但是我不知道我怎么能说mongodb的notexists或者union关键字。如何编写mongodb查询?我应该搜索哪些关键字?

  1. select p.*, "to_top" as list
  2. from percentages p
  3. where p.percentage > 5
  4. and p.updatetime > sysdate - 1/24
  5. and not exists (select 1
  6. from items i
  7. where i.id = p.p_id
  8. and i.seller = p.seller)
  9. order by p.percentage desc
  10. union
  11. select p2.*, "to_bottom" as list
  12. from percentages p2
  13. where p2.percentage > 5
  14. and p2.updatetime > sysdate - 1/24
  15. and exists (select 1
  16. from items i2
  17. where i2.id = p2.p_id
  18. and i2.seller = p2.seller)
  19. order by p2.percentage desc
3xiyfsfu

3xiyfsfu1#

根本没有 UNION 对于mongodb。幸运的是,每个查询都在同一个集合上执行,并且条件非常接近,所以我们可以实现“mongo-way”查询。

解释

通常,所有复杂的sql查询都是通过mongodb聚合框架完成的。
我们筛选文档的依据 percentage / updatetime . 解释为什么我们需要使用 $expr sql联接/子查询是使用$lookup运算符完成的。
sql语句 SYSDATE 在mongodb中 NOW 或者 CLUSTER_TIME 变量。

  1. db.percentages.aggregate([
  2. {
  3. $match: {
  4. percentage: { $gt: 5 },
  5. $expr: {
  6. $gt: [
  7. "$updatetime",
  8. {
  9. $subtract: [
  10. ISODate("2020-06-14T13:00:00Z"), //Change to $$NOW or $$CLUSTER_TIME
  11. 3600000
  12. ]
  13. }
  14. ]
  15. }
  16. }
  17. },
  18. {
  19. $lookup: {
  20. from: "items",
  21. let: {
  22. p_id: "$p_id",
  23. seller: "$seller"
  24. },
  25. pipeline: [
  26. {
  27. $match: {
  28. $expr: {
  29. $and: [
  30. {
  31. $eq: [ "$$p_id", "$id"]
  32. },
  33. {
  34. $eq: [ "$$seller", "$seller"]
  35. }
  36. ]
  37. }
  38. }
  39. },
  40. {
  41. $limit: 1
  42. }
  43. ],
  44. as: "items"
  45. }
  46. },
  47. {
  48. $addFields: {
  49. list: {
  50. $cond: [
  51. {
  52. $eq: [{$size: "$items"}, 0]
  53. },
  54. "$to_top",
  55. "$to_bottom"
  56. ]
  57. },
  58. items: "$$REMOVE"
  59. }
  60. },
  61. {
  62. $sort: { percentage: -1 }
  63. }
  64. ])

mongoplayground公司
注意:mongodb聚合有$facet操作符,允许对同一集合执行不同的查询。
架构:

  1. db.percentages.aggregate([
  2. {$facet:{
  3. q1:[...],
  4. q2:[...],
  5. }},
  6. //We apply "UNION" the result documents for each pipeline into single array
  7. {$project:{
  8. data:{$concatArrays:["$q1","$q2"]}
  9. }},
  10. //Flatten array into single object
  11. {$unwind:"$data"}
  12. //Replace top-level document
  13. {$replaceWith:"$data"}
  14. ])

mongoplayground公司

展开查看全部
4uqofj5v

4uqofj5v2#

为什么不将mangodb数据导入oracle并使用sql(这比mango更简单、更强大)

相关问题