Guest User

Untitled

a guest
Jul 10th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. {
  2. "_id" : ObjectId("5b453cc7799fb211dc44a1e8"),
  3. "id" : 1.0,
  4. "nestedDoc" : {
  5. "nestedArray" : [
  6. {
  7. "field1" : "value1",
  8. "field2" : "value2",
  9. "field3" : "value3"
  10. },
  11. {
  12. "field1" : "value11",
  13. "field2" : "value21",
  14. "field3" : "value31"
  15. },
  16. {
  17. "field1" : "value12",
  18. "field2" : "value22",
  19. "field3" : "value32"
  20. }
  21. ]
  22. }
  23. }
  24. {
  25. "_id" : ObjectId("5b453d23799fb211dc44a1e9"),
  26. "id" : 2.0,
  27. "nestedDoc" : {
  28. "nestedArray" : [
  29. {
  30. "field1" : "value1",
  31. "field2" : "value29",
  32. "field3" : "value39"
  33. },
  34. {
  35. "field1" : "value118",
  36. "field2" : "value281",
  37. "field3" : "value381",
  38. "field4" : "value281"
  39. },
  40. {
  41. "field1" : "value172",
  42. "field2" : "value272",
  43. "field3" : "value372"
  44. }
  45. ]
  46. }
  47. }
  48.  
  49. db.test1.aggregate(
  50. [
  51. // Stage 1 : filter documents
  52. {
  53. $match: {
  54. id:1
  55. }
  56. },
  57. // Stage 2 : count array size and return only it.
  58. {
  59. $project: {
  60. arraySize:{$size:"$nestedDoc.nestedArray"},
  61. _id:0
  62. }
  63. },
  64. ]
  65. );
  66.  
  67. db.test1.aggregate(
  68. [
  69. // Stage 1 count array size for each document
  70. {
  71. $project: {
  72. _id:0,
  73. arraySize:{$size:"$nestedDoc.nestedArray"}
  74. }
  75. },
  76. // Stage 2 group all documents and sum arraySize
  77. {
  78. $group: {
  79. _id:null,
  80. totalArraysSize:{$sum:"$arraySize"}
  81. }
  82. },
  83. ]
  84. );
Add Comment
Please, Sign In to add comment