带有“或"条件的 MongoDB 查询

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

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

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.

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

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.

推荐答案

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

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

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

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

发布评论

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

>www.elefans.com

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