0

I have a MongoDB collection of documents with the following "schema" :

{
  field1: value1,
  field2: value2
}

I want to run a query with "$match" in a pipeline to check the equality of field1 and field2 values.

Something like "field1" == "field2".

How can I do this?

Thank you people!

2 Answers2

4
db.c.aggregate([{
    $project : {
        equal : {
            $eq : ["$field1", "$field2"]  // to judge like your :  "valueof(field1) == valueof(field2)"
        },
        doc : "$$ROOT"   // store the whole document, this is optional
    }
}, {
    $match : {
        equal : true   // filter to get documents only satisfy : "valueof(field1) == valueof(field2)"
    }
}]);
Wizard
  • 4,341
  • 1
  • 15
  • 13
  • 1
    @i alarmed alien, Perhaps I thought it's enough was wrong. Thanks for the remind. – Wizard Oct 27 '14 at 15:17
  • Thanks! It worked.. But what is the meaning of 'doc : "$$ROOT"' ? – Efstathios Chatzikyriakidis Oct 28 '14 at 17:51
  • @Efstathios Chatzikyriakidis: It represents the current document of previous stage. For example, if there is a document {_id:1, a:1, b:2} in your collection, then doc:"$$ROOT" will produce a field as {doc : {_id:1, a:1, b:2}}. It's optional as I comment in code block, I made it because I'm not sure which fields you want to project at last, so I project the entire document. – Wizard Oct 29 '14 at 00:44
-1

You will need to do something like this:

db.collection.aggregate([{$match:{field1:value1 , field2:value1}}])
vmr
  • 1,895
  • 13
  • 24