You cannot compare a field with the value of another field with a normal query matching. However, you can do this using the aggregation structure:
db.so.aggregate( [ { $match: …your normal other query… }, { $match: { $eq: [ '$modified', '$sync' ] } } ] );
I put ... your usual other query ... where you can make this bit using an index. Therefore, if you want to do this only for documents, where the name charles field you can do:
db.so.ensureIndex( { name: 1 } ); db.so.aggregate( [ { $match: { name: 'charles' } }, { $project: { modified: 1, sync: 1, name: 1, eq: { $cond: [ { $gt: [ '$modified', '$sync' ] }, 1, 0 ] } } }, { $match: { eq: 1 } } ] );
When entering:
{ "_id" : ObjectId("520276459bf0f0f3a6e4589c"), "modified" : 73845345, "sync" : 73234 } { "_id" : ObjectId("5202764f9bf0f0f3a6e4589d"), "modified" : 4, "sync" : 4 } { "_id" : ObjectId("5202765b9bf0f0f3a6e4589e"), "modified" : 4, "sync" : 4, "name" : "charles" } { "_id" : ObjectId("5202765e9bf0f0f3a6e4589f"), "modified" : 4, "sync" : 45, "name" : "charles" } { "_id" : ObjectId("520276949bf0f0f3a6e458a1"), "modified" : 46, "sync" : 45, "name" : "charles" }
This returns:
{ "result" : [ { "_id" : ObjectId("520276949bf0f0f3a6e458a1"), "modified" : 46, "sync" : 45, "name" : "charles", "eq" : 1 } ], "ok" : 1 }
If you want more fields, you need to add them to $project .