条件的MongoDB查询

条件的MongoDB查询

本文介绍了具有“或"条件的MongoDB查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

解决方案

我以为我会在将来有人偶然发现此页面的情况下进行更新.从1.5.3版开始,mongo现在支持真正的$ or运算符: http ://www.mongodb.org/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: http://www.mongodb.org/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查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:36