Akash Salunkhe
Akash Salunkhe

Reputation: 314

Query access variable outside query based on condition in NodeJS and MongoDB

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
}

Upvotes: 1

Views: 657

Answers (1)

turivishal
turivishal

Reputation: 36104

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

Upvotes: 1

Related Questions