1

I have a schema like below:

[
  {
    "_id": 1,
    "showResult": true,
    "subject": "History",
  },
  {
    "_id": 2,
    "showResult": false,
    "subject": "Math",
  }
]

and an object in JS like below:

result = {
 "History": 22,
 "Math": 18
}

I am using aggregate to process query, in between i need to find score based on subject field in the document if showResult field is true i.e to access result variable inside query as map result[$subject]

My query:

db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      "score":{$cond: { if: { $eq: [ "$showResult", true ] }, then: subjectObj[$subject], else: null }}

    }
  }
])

can this be done in MongoDB, i want result like below:

{
 _id: 1,
 score: 22
}
1
  • my next aggregation pipeline depends on the result form this part Commented Nov 5, 2020 at 15:41

1 Answer 1

1

I think query is little costly than JS code, but i am adding the query if it will help you as per your question,

  • $match showResult is true
  • $project to show required fields, $reduce to iterate loop of result after converting from object to array using $objectToArray, check condition if subject match then return matching score
let result = {
 "History": 22,
 "Math": 18
};
db.collection.aggregate([
  { $match: { showResult: true } },
  {
    $project: {
      _id: 1,
      score: {
        $reduce: {
          input: { $objectToArray: result },
          initialValue: 0,
          in: {
            $cond: [{ $eq: ["$$this.k", "$subject"] }, "$$this.v", "$$value"]
          }
        }
      }
    }
  }
])

Playground

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.