0

Given the collection "example":

{_id: 1, prediction: "H", result: "A"}
{_id: 2, prediction: "H", result: "H"}
{_id: 3, prediction: "A", result: "A"}

What do I need to do to find records where the prediction and result values match? ie. documents 2 and 3?

Finding all the "H" predictions is:

db.example.find( { prediction: "H" } )

But I need to replace the literal "H" with the value in the result field of the same document.

Edit: Sorry, I should have said that I was using Mongo 3.6.

Spuggiehawk
  • 180
  • 2
  • 4
  • 12

3 Answers3

2

You should be able to do this with an aggregation query, try out the $redact stage:

db.test.aggregate(
   [
     { $redact: {
        $cond: {
           if: { $eq: [ "$prediction", "$result" ] },
           then: "$$DESCEND",
           else: "$$PRUNE"
         }
       }
     }
   ]
);

This will yield the result:

{ "_id" : 2, "prediction" : "H", "result" : "H" }
{ "_id" : 3, "prediction" : "A", "result" : "A" }

More info on redact can be found here - https://docs.mongodb.com/manual/reference/operator/aggregation/redact/#redact-aggregation

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77
0

You can use agregation

    db.example.aggregate(
       [
         {
           $project:
              {
                _id: 1,
                prediction: 1,
                result: 1,
                compare: { $eq: [ "$prediction", "$result" ] }
              }
         },
         {
           $match:
              {
                compare: true
              }
         }
       ]
    )
Bùi Đức Khánh
  • 3,975
  • 6
  • 27
  • 43
  • 1
    This is very similar to another solution I found: db.example.find( { $expr: { $eq: ["$prediction", "$result"] } } ). I like these answers because they're efficient and exactly what I was looking for. – Spuggiehawk Feb 28 '18 at 10:21
0

If you are using 3.6, this will work. refer this

db.getCollection('TEST').find( { $where: function() {
   return this.prediction == this.result
} })

Result :

{
    "_id" : 2,
    "prediction" : "H",
    "result" : "H"
}
{
    "_id" : 3,
    "prediction" : "A",
    "result" : "A"
}
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37