Compare two date fields in MongoDB

前端 未结 6 1331
别跟我提以往
别跟我提以往 2020-12-10 04:36

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.

I tried

{\'m         


        
6条回答
  •  悲哀的现实
    2020-12-10 05:22

    For MongoDB 3.6 and newer:

    The $expr operator allows the use of aggregation expressions within the query language, thus you can do the following:

    db.test.find({ "$expr": { "$gt": ["$modified", "$sync"] } })
    

    or using aggregation framework with $match pipeline

    db.test.aggregate([
        { "$match": { "$expr": { "$gt": ["$modified", "$sync"] } } }
    ])
    

    For MongoDB 3.0+:

    You can also use the aggregation framework with the $redact pipeline operator that allows you to process the logical condition with the $cond operator and uses the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "remove" the document where the condition was false.

    Consider running the following aggregate operation which demonstrates the above concept:

    db.test.aggregate([
        { "$redact": {
            "$cond": [
                { "$gt": ["$modified", "$sync"] },
                "$$KEEP",
                "$$PRUNE"
            ]
        } }
    ])
    

    This operation is similar to having a $project pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match, except that $redact uses a single pipeline stage which is more efficient:

提交回复
热议问题