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

查看:1512
本文介绍了比较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' ] } }
] );

我把...正常的其他查询...在那里,你可以使这个位使用索引。所以,如果你想为名称字段 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" }

/ p>

This returns:

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

如果你想要任何更多的领域,你需要添加它们在t他 $ project

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

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

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