比较 MongoDB 中的版本 [英] Comparing versions in MongoDB
问题描述
只是想知道是否有人能想出更聪明的方法来做到这一点...
just wondering if anyone can come up with a smarter way to do this...
假设我在 MongoDB 中有一些带有版本属性的文档,例如{ ..., version: { major: 1, minor: 2, patch: 13 } }
或 { ..., version: "1.2.13" }
如果更容易.
Let's say I have some documents in MongoDB with a version property, for example something like
{ ..., version: { major: 1, minor: 2, patch: 13 } }
, or { ..., version: "1.2.13" }
if it is easier.
查找所有版本为 X.Y.Z 或更高版本的文档的最简单方法是什么?我现在的做法基本上是一个巨大的 $and 子句.
What's the easiest way to find all documents that have version X.Y.Z or above? The way I'm doing it now is basically a huge $and clause.
推荐答案
你的第一个设计其实很不错.原因是你可以索引字段major
、minor
和patch
以便快速读取.
Your first design is actually very good. The reason is because you can index the fields major
, minor
and patch
for fast reads.
查询数据实际上比使用$and
查询容易得多.您可以只对匹配字段使用基本查询:
Querying the data is actually much easier than using the $and
query. You can just use a basic query on matching fields:
例如
db.versions.find({major:1,minor:2,patch:20}) //give me documents of version 1.2.20
db.versions.find({major:1}) //give me all documents with major version 1
db.versions.find({major:1,minor:{$gte:2,$lte:5}}) //give me all documents of major version and minor versions between 2 and 5 inclusive.
你可以创建一个像
db.versions.ensureIndex({major:1,minor:1,patch:1})
$and
查询主要用于在同一字段上多次运行更复杂查询的情况.例如,如果您想获得主要版本 1 和 2,您可以使用 $and
.
The $and
query is mainly for the case where you want to run a more complex query on the same field multiple times. For instance, if you want to get major versions 1 and 2, you can use $and
.
db.versions.find({major:1,major:2})
实际上只会返回主要版本为 2 的文档.但是,db.versions.find({a:$all:[1,2]})
在这种情况下也可以工作.理想情况下,您应该尽可能避免使用 $and
,因为它实际上会为 $and
数组中的每个表达式生成多个查询并执行联合.这比我上面提供的查询示例要贵得多.
db.versions.find({major:1,major:2})
will actually only return documents with major version 2. However, db.versions.find({a:$all:[1,2]})
would work too in this case. You should ideally avoid using $and
when you can because it actually spawns multiple queries for each expression in the $and
array and performs a union. This is much more expensive than the query samples I provided above.
这篇关于比较 MongoDB 中的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!