Advertisement
Anatolyukropov

$Match, $OR, $group

Sep 29th, 2020
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. Hello guys, if you can help me I need help with a query.
  2. I have a document called Response with 3 fields, here an example:
  3. [
  4. {
  5. "userId": "1",
  6. "questionId": "1",
  7. "answerIndex": 1
  8. },
  9. {
  10. "userId": "1",
  11. "questionId": "2",
  12. "answerIndex": 0
  13. },
  14. {
  15. "userId": "2",
  16. "questionId": "1",
  17. "answerIndex": 1
  18. }
  19.  
  20. I need to count how much users replied question 1 with answer 1 and question 2 with answer 0.
  21. I tried to write this query:
  22.  
  23. db.responses.count( { $and: [ { $and : [ { questionId: { $eq: "1" } }, { answerIndex: { $eq: 1 } } ] }, { $and : [ { questionId: { $eq: "2" } }, { answerIndex: { $eq: 0 } } ] } )
  24.  
  25. but it's not working because I don't know how to isolate the user.
  26.  
  27. I'd be very grateful if anyone can help me, thanks!
  28. I think I have to use $group on userId but I don't know exactly how
  29.  
  30.  
  31. db.collection.aggregate([
  32. {
  33. "$match": {
  34. $or: [
  35. {
  36. questionId: 1,
  37. answerIndex: 1
  38. },
  39. {
  40. questionId: 2,
  41. answerIndex: 0
  42. }
  43. ]
  44. }
  45. },
  46. {
  47. $group: {
  48. _id: {
  49. userId: "$userId"
  50. },
  51. count: {
  52. $sum: 1
  53. }
  54. }
  55. }
  56. ])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement