Christopher
Christopher

Reputation: 627

MongoDB, How Do I combine a find and sort with the $cond in aggregation?

I have written a find query, which works, the find query returns records where name and level exist

db.docs.find( { $and: [{name:{$exists:true}},{level:{ $exists:true}} ] },{_id:0, name:1}).sort({"name":1})

and now want to combine it with something like the code below which also works, but needs to be merged with the above to pull the correct data

db.docs.aggregate(
   [
      {
         $project:
           {
             _id:0,
             name: 1,
             Honours:
               {
                 $cond: { if: { $gte: [ "$level", 8 ] }, then: "True", else: "False" }
               }
           }
      }
   ]
)

The find query returns records where name and level exist, but I need to enhance the result with new column called Honours, showing True of False depending on whether the level is gte (greater than or equal to 8)

So I am basically trying to combine the above find filter with the $cond function (which I found and modified example here : $cond)

I tried the below and a few other permutations to try and make find and sort with the $project and$cond aggregate, but it returned errors. I am just very new to how to construct mongodb syntax to make it all fit together. Can anyone please help?

db.docs.aggregate(
   [{{ $and: [{name:{$exists:true}},{level:{ $exists:true}} ] },{_id:0, name:1}).sort({"name":1}
      {
         $project:
           {
             _id:0,
             name: 1,
             Honours:
               {
                 $cond: { if: { $gte: [ "$level", 8 ] }, then: "True", else: "False" }
               }
           }
      }
}
   ]
)

Upvotes: 1

Views: 508

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Try below aggregation pipeline :

db.docs.aggregate([
  /** $match is used to filter docs kind of .find(), lessen the dataset size for further stages */
  {
    $match: {
      $and: [{ name: { $exists: true } }, { level: { $exists: true } }]
    }
  },
  /** $project works as projection - w.r.t. this projection it will lessen the each document size for further stages */
  {
    $project: {
      _id: 0,
      name: 1,
      Honours: {
        $cond: { if: { $gte: ["$level", 8] }, then: "True", else: "False" }
      }
    }
  },
  /** $sort should work as .sort() */
  { $sort: { name: 1 } }
]);

Upvotes: 0

Related Questions