比较MongoDB中的两个date字段

在我的collections中,每个文档有2个date,修改和同步。 我想find那些修改>同步,或同步不存在。

我试过了

{'modified': { $gt : 'sync' }} 

但是没有显示出我的预期 有任何想法吗?

谢谢

您无法将字段与正常查询匹配的其他字段的值进行比较。 但是,您可以使用聚合框架来执行此操作:

 db.so.aggregate( [ { $match: …your normal other query… }, { $match: { $eq: [ '$modified', '$sync' ] } } ] ); 

我把…你正常的其他查询…在那里,因为你可以使这一点使用索引。 所以,如果你只想做这个只有name字段为charles文档,你可以这样做:

 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 } } ] ); 

随着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" } 

这返回:

 { "result" : [ { "_id" : ObjectId("520276949bf0f0f3a6e458a1"), "modified" : 46, "sync" : 45, "name" : "charles", "eq" : 1 } ], "ok" : 1 } 

如果你想要更多的领域,你需要将它们添加到$project

只是

 db.collection.find({$where:"this.modified>this.sync"}) 

 Kobkrits-MacBook-Pro-2:~ kobkrit$ mongo MongoDB shell version: 3.2.3 connecting to: test > db.time.insert({d1:new Date(), d2: new Date(new Date().getTime()+10000)}) WriteResult({ "nInserted" : 1 }) > db.time.find() { "_id" : ObjectId("577a619493653ac93093883f"), "d1" : ISODate("2016-07-04T13:16:04.167Z"), "d2" : ISODate("2016-07-04T13:16:14.167Z") } > db.time.find({$where:"this.d1<this.d2"}) { "_id" : ObjectId("577a619493653ac93093883f"), "d1" : ISODate("2016-07-04T13:16:04.167Z"), "d2" : ISODate("2016-07-04T13:16:14.167Z") } > db.time.find({$where:"this.d1>this.d2"}) > db.time.find({$where:"this.d1==this.d2"}) > 

使用JavaScript,使用foreach并将date转换为toDateString()

 db.ledgers.find({}).forEach(function(item){ if(item.fromdate.toDateString() == item.todate.toDateString()) { printjson(item) } }) 

现在,您的查询正试图返回所有结果,使modified字段大于'sync'一词。 尝试摆脱sync周围的引号,看看是否修复任何东西。 否则,我做了一些调查,发现了这个问题 。 你试图做的事情可能在一个查询中是不可能的,但是一旦你从数据库中取出所有的东西,你应该能够操纵你的数据。

要解决这个问题,而不汇总改变你的查询: {'modified': { $gt : ISODate(this.sync) }}