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方式,我需要的结果集将是这三个的UNION(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运算符是 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屋!