[英]MongoDB: Select all elements where 2 fields have the same date
I have a collection like this: 我有一个这样的收藏:
{
_id: ObjectId("53c4000f821bc31e3ec90140"),
foo: "bar",
created: ISODate("2014-07-09T02:15:49.000+02:00"),
updated: ISODate("2014-07-09T02:15:49.000+02:00")
},
{
_id: ObjectId("53c4000f821bc4dw3ec90140"),
foo: "bar",
created: ISODate("2014-07-09T02:15:49.000+02:00"),
updated: ISODate("2014-07-09T02:19:49.000+02:00")
},
Now I want to select all elements of the collection where created == updated . 现在,我要选择集合中创建==更新的所有元素 。 In this example the query should return only the first element.
在此示例中,查询应仅返回第一个元素。
I tried this: db.foo.find( {$where: "this.created == this.updated"})
but I get no results :-( 我尝试了这个:
db.foo.find( {$where: "this.created == this.updated"})
但没有得到结果:-(
Object comparisons don't work like that in JavaScript. 对象比较不能像JavaScript那样工作。 You need to compare a "value" and not the whole object:
您需要比较一个“值”而不是整个对象:
db.foo.find(function(){ return this.created.valueOf() == this.updated.valueOf() })
So the .valueOf()
is the key here. 所以
.valueOf()
是这里的关键。 And that is just a shorthand for $where
when you have no other conditions. 当您没有其他条件时,这只是
$where
的简写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.