具有“或"条件的MongoDB查询

编程入门 行业动态 更新时间:2024-10-22 13:54:01
本文介绍了具有“或"条件的MongoDB查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,我有一个嵌入式文档来跟踪组成员身份.每个嵌入的文档都有一个指向另一个集合中该组的ID,一个开始日期和一个可选到期日期.

我想查询组的当前成员. 当前"表示开始时间小于当前时间,到期时间大于当前时间或为空.

此条件查询完全阻止了我.我可以通过运行两个查询并合并结果来做到这一点,但这似乎很丑陋,需要立即加载所有结果.或者,我可以将过期时间默认为将来的某个任意日期,但这似乎更丑陋,而且可能很脆弱.在SQL中,我只用((expires> = Now())OR(expires IS NULL)")表示它,但我不知道如何在Mongo中做到这一点.

有什么想法吗?非常感谢.

解决方案

我以为我会在将来有人偶然发现此页面的情况下进行更新.从1.5.3版开始,mongo现在支持真正的$ or运算符: http ://www.mongodb/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

您对((expires> = Now())OR(expires IS NULL)")的查询现在可以呈现为:

{$or: [{expires: {$gte: new Date()}}, {expires: null}]}

So I have an embedded document that tracks group memberships. Each embedded document has an ID pointing to the group in another collection, a start date, and an optional expire date.

I want to query for current members of a group. "Current" means the start time is less than the current time, and the expire time is greater than the current time OR null.

This conditional query is totally blocking me up. I could do it by running two queries and merging the results, but that seems ugly and requires loading in all results at once. Or I could default the expire time to some arbitrary date in the far future, but that seems even uglier and potentially brittle. In SQL I'd just express it with "(expires >= Now()) OR (expires IS NULL)" -- but I don't know how to do that in Mongo.

Any ideas? Thanks very much in advance.

解决方案

Just thought I'd update in-case anyone stumbles across this page in the future. As of 1.5.3, mongo now supports a real $or operator: www.mongodb/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

Your query of "(expires >= Now()) OR (expires IS NULL)" can now be rendered as:

{$or: [{expires: {$gte: new Date()}}, {expires: null}]}

更多推荐

具有“或"条件的MongoDB查询

本文发布于:2023-11-22 20:43:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   quot   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!