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

后端 未结 2 1831
后悔当初
后悔当初 2021-01-03 22:34

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: { $         


        
相关标签:
2条回答
  • Basically, you are trying to perform a self join. An operation not supported by MongoDB.

    Concerning the $eq operator, as you guessed:

    • By design, the $eq comparison query operator match a field against a value.
    • But the $eq comparison aggregation operator compare the value of two expressions.

    I don't know any other way to perform what you need than using an extra $project step as you suggested.

    Please note this is not significantly more expensive as, anyway, your query cannot use any index and MongoDB will do a full scan.

    0 讨论(0)
  • 2021-01-03 23:04

    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" } );
    
    0 讨论(0)
提交回复
热议问题