comparing two fields from the same document

7,708 views
Skip to first unread message

geoffeg

unread,
Aug 24, 2012, 5:31:03 PM8/24/12
to mongod...@googlegroups.com
I know there is no way to compare two fields from the same document in MongoDB 2.0:

db.foo.save({
    "_id" : ObjectId("5037f1d19cb590b9b72a2558"),
    "update-date" : ISODate("1970-01-01T00:00:00Z"),
    "read-date" : ISODate("2012-08-24T21:27:37.070Z")
})

db.foo.find({"read-date' : { $gt : "update-date" }})

Is there some way to do this in 2.2 with the new aggregation framework? Dates or integers (epoch for instance) would be fine.

Thanks,
Geoff

lwb

unread,
Aug 27, 2012, 11:56:14 AM8/27/12
to mongod...@googlegroups.com
Hi Geoff, 

Yes, you will be able to do this with the new aggregation framework in 2.2, which should be released in the next few weeks. In this framework, you'll be able to compare fields from the same document using the pipeline operator $match. The documentation is here: http://docs.mongodb.org/manual/reference/aggregation/ .  

Gianfranco

unread,
Aug 27, 2012, 12:05:40 PM8/27/12
to mongod...@googlegroups.com
Hi Geoff,

There is a way to do it in JavaScript with the $where operator but it's using the language components to do this and not MongoDB's.


db.foo.find({ $where: "this.read-date > this.update-date" })

So if you have a lot to do a lot of queries like this is better to use the Aggregation Framework as Louisa said.

Gianfranco

On Friday, August 24, 2012 5:31:03 PM UTC-4, geoffeg wrote:

Stephen Steneker

unread,
Aug 30, 2012, 7:17:56 AM8/30/12
to mongod...@googlegroups.com
Hi Geoff,

Using the aggregation framework, here is an example that will find documents that have an updateDate newer than the readDate:

        db.foo.aggregate(
                { $project: {
                        readDate: 1,
                        updateDate: 1,
                        isUpdated: { $gt:["$updateDate","$readDate"] }
                }},
                { $match : {
                        isUpdated : true,
                }}
        )

Computed fields (such as the `isUpdated` date comparison in this example) can be added in a $project or $group command, and filtered using $match.

Cheers,
Stephen 
Reply all
Reply to author
Forward
0 new messages