比较 MongoDB 中的两个日期字段 [英] Compare two date fields in MongoDB

查看:54
本文介绍了比较 MongoDB 中的两个日期字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的收藏中,每个文档都有 2 个日期,已修改和同步.我想找到那些修改过的 > 同步,或者同步不存在的.

in my collection each document has 2 dates, modified and sync. I would like to find those which modified > sync, or sync does not exist.

我试过了

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

但它没有显示出我的预期.有什么想法吗?

but it's not showing what I expected. Any ideas?

谢谢

推荐答案

您不能将一个字段与另一个具有正常查询匹配的字段的值进行比较.但是,您可以使用聚合框架执行此操作:

You can not compare a field with the value of another field with the normal query matching. However, you can do this with the aggregation framework:

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

我把……你普通的其他查询……放在那里,因为你可以让那个位使用索引.因此,如果您只想对 name 字段为 charles 的文档执行此操作,您可以执行以下操作:

I put …your normal other query… in there as you can make that bit use the index. So if you want to do this for only documents where the name field is charles 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 } }
] );

随着输入:

{ "_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中添加它们.

If you want any more fields, you need to add them in the $project.

这篇关于比较 MongoDB 中的两个日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆