node.js - Compare two date fields in MongoDB -
in collection each document has 2 dates, modified , sync. find modified > sync, or sync not exist.
i tried
{'modified': { $gt : 'sync' }}
but it's not showing expected. ideas?
thanks
you can not compare field value of field normal query matching. however, can aggregation framework:
db.so.aggregate( [ { $match: …your normal other query… }, { $match: { $eq: [ '$modified', '$sync' ] } } ] );
i put …your normal other query… in there can make bit use index. if want documents name
field charles
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 } } ] );
with input:
{ "_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 want more fields, need add them in $project
.
Comments
Post a Comment