Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Hello guys, if you can help me I need help with a query.
- I have a document called Response with 3 fields, here an example:
- [
- {
- "userId": "1",
- "questionId": "1",
- "answerIndex": 1
- },
- {
- "userId": "1",
- "questionId": "2",
- "answerIndex": 0
- },
- {
- "userId": "2",
- "questionId": "1",
- "answerIndex": 1
- }
- I need to count how much users replied question 1 with answer 1 and question 2 with answer 0.
- I tried to write this query:
- db.responses.count( { $and: [ { $and : [ { questionId: { $eq: "1" } }, { answerIndex: { $eq: 1 } } ] }, { $and : [ { questionId: { $eq: "2" } }, { answerIndex: { $eq: 0 } } ] } )
- but it's not working because I don't know how to isolate the user.
- I'd be very grateful if anyone can help me, thanks!
- I think I have to use $group on userId but I don't know exactly how
- db.collection.aggregate([
- {
- "$match": {
- $or: [
- {
- questionId: 1,
- answerIndex: 1
- },
- {
- questionId: 2,
- answerIndex: 0
- }
- ]
- }
- },
- {
- $group: {
- _id: {
- userId: "$userId"
- },
- count: {
- $sum: 1
- }
- }
- }
- ])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement