Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : querying documents with two equal fields, $match and $eq

Tags:

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?

like image 477
Peter Sampson Avatar asked Jun 10 '15 17:06

Peter Sampson


People also ask

How do I match two fields in MongoDB?

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.

How do I write an equal query in MongoDB?

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.

Can we use two group by in same query in MongoDB?

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.


1 Answers

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" } ); 
like image 110
Shivangi Gupta Avatar answered Oct 14 '22 21:10

Shivangi Gupta