mongodb 中同一个集合的联合 [英] union on same collection in mongodb
问题描述
我需要最可行的方法来搜索具有以下结构的文档.
I need the most viable way to search docs with the following structure.
{ _id:"",
var1: number,
var2: number,
var3: number,
}
在sql方式中,我需要的结果集是这三个的联合(n条记录按var1排序,n条记录按var2排序,n条记录按var3排序)
In the sql way the resultset i need would be UNION of these three (n records sorted by var1,n records sorted by var2,n records sorted by var3)
对于 UNION,我希望删除重复项.
with UNION I expect the duplicates to be removed.
作为 mongodb 的新手,我无法找到为此类操作编写查询的正确方法,我相信这在 mongodb 中一定是可能的.
Being new to mongodb i am not able to find the right way to write a query for such an operation, i believe it must be possible in mongodb.
如果不可能,请您建议一个替代的 nosql 解决方案.
If in case its not possible, could you please suggest an alternate nosql solution.
推荐答案
最接近您正在寻找的 MongoDB 运算符是 $or
,但这与 SQL UNION 将两个单独的查询合并为一个结果.MongoDB 查询始终针对单个集合,但 $or
允许您有多个查询子句.
The closest MongoDB operator to what you are looking for is an $or
, but that isn't quite the same as an SQL UNION which combines two separate queries into a single result. MongoDB queries are always against a single collection, but $or
allows you to have multiple query clauses.
例如:
db.collection.find(
// Find documents matching any of these values
{$or:[
{var1: 123},
{var2: 456},
{var3: 789}
]}
).sort(
// Sort in ascending order
{var1:1, var2:1, var3:1}
)
由于您只能查询单个集合,因此结果将已在文档级别进行重复数据删除,并且如果指定了所有结果,则所有结果将共享相同的排序顺序.
Since you are limited to querying a single collection, results will already be de-duplicated at the document level and all results will share the same sort order if one is specified.
如果要在 MongoDB 中模拟 UNION(或其他处理多个集合/查询的操作),则必须编写多个查询并在应用程序代码中合并结果集.
If you want to simulate a UNION (or other operation working with multiple collections/queries) in MongoDB, you will have to write multiple queries and merge the result sets in your application code.
这篇关于mongodb 中同一个集合的联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!