可以在MongoDB查询中使用严格的JSON $ date? [英] Can strict JSON $dates be used in a MongoDB query?

查看:672
本文介绍了可以在MongoDB查询中使用严格的JSON $ date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MongoDB的 BSON的严格JSON表示

I'm trying to write a date comparison query using MongoDB's strict JSON representation of BSON.

我希望它在MongoDB shell(v2.4.3)中工作

I'd like it to work in the MongoDB shell (v2.4.3)

ve尝试...

> db.myTimes.insert({"at": new Date("2020-01-01")})



对日期> 2010使用非严格查询,没问题:



Using non-strict query for date > 2010, no problem:

> db.myTimes.find({"at": {"$gt": new Date("2010-01-01")}})
{ "_id" : ObjectId([snipped]), "at" : ISODate("2020-01-01T00:00:00Z") }



使用严格的JSON查询,但是...



Using strict JSON query, however... NO DICE

> db.myTimes.find({"at": {"$gt": {"$date":"2010-01-01T00:00:00Z"}}})
> db.myTimes.find({"at": {"$gt": {"$date":"2010-01-01"}}})
> db.myTimes.find({"at": {"$gt": {"$date": 1262304000000}}})
> db.myTimes.find({"at": {"$lte": {"$date": 1262304000000}}})

(可以看到,我尝试了ISO8601的日期,时代,并且还将我的 $ gt 更改为 $ lte 的理论是这些将是相互排斥的,所以他们之一应该返回一些东西: - )

(As you can see, I tried ISO8601 dates, epoch times, and also changing my $gt to $lte on the theory that these would be mutually exclusive, so one of them should return something :-)

感谢任何指针!

-B

推荐答案

我不确定一切都表明使用严格的JSON构建有效的查询是不可能的。虽然您可以运行 $ date $ gt $ gte $ lt $ lte 似乎像你的情况一样,总是被评估为code> false 。

I am not sure but everything suggests that it is impossible to build valid query using strict JSON. Although you can run query combining $date with $gt, $gte, $lt, $lte it seems, like in your case, to be always evaluated as false.

$ date $ ne $ nin 它将匹配收集中的每个文档,所以我认为它证实了以前的观察。

When you combine $date with $ne or $nin it will match every document in collection so I think it confirms previous observation.

更重要的是什么你尝试得到这样的精确匹配 db.foo.find({at:{$ date:2010-01-01T00:00:00Z}})你会得到无效的操作错误(10068)。

What is more important when you try to get exact match like this db.foo.find({at: {"$date":"2010-01-01T00:00:00Z"}}) you will get invalid operator error (10068).

我的猜测是尝试使用 $ date

doc = {at: {"$date":"2010-01-01T00:00:00Z"}}

它不被评估为日期,没有办法将这样的文档插入到集合中。
如您所见,似乎严格的JSON只能通过像 mongoimport 这样的工具正确解析。
这里有类似的问题:有没有办法在严格JSON模式下运行MongoDB shell(或tojson方法)?

it is not evaluated as date and there is no way to insert document like this into collection. As you see it seems that strict JSON is parsed correctly only by tools like mongoimport. There is similar question here: Is there a way to run MongoDB shell (or tojson method) in strict JSON mode?.

这篇关于可以在MongoDB查询中使用严格的JSON $ date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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