What is the best way to return all documents in a collection if I want document.a == document.b?
I've tried
db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }])
But it returns with no errors or results, because I assume it is literally matching strings "$a" and "$b". Is there a different way to specify that these are fields?
db.collection.aggregate([ { $project: { eq: { $cond: [ { $eq: [ '$a', '$b' ] }, 1, 0 ] } } }, { $match: { eq: 1 } }])
The above works, but requires the additional step of querying again with whatever documents it found or projecting all possible fields.
Is there a better way for achieving this query?
MongoDB compare two fields in the same document In this topic, you will learn to compare two fields in the same document. You can use the $where operator to compare the fields. When we have a given condition where we have to compare multiple properties on the same field. Let us understand with the help of an example.
The equality operator( $eq ) is used to match the documents where the value of the field is equal to the specified value. In other words, the $eq operator is used to specify the equality condition. Important Points: If the given value is a document, then the order of the fields in the document is important.
In the MongoDB database, group by is used to group the data from the collection. We can also use the aggregation function as well and group the method. The aggregate function is used in multiple conditions. We can group by single as well as multiple fields from the collection.
If I understood your question right you want those documents that have same values in field1 and field2.
For this try
db.coll.find({$where: function() { return this.field1 == this.field2 } } );
or more compact
db.coll.find({ $where : "this.field1 == this.field2" } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With