Har*_*vic 2 mongodb mongodb-query
我有下一个情况.
在parameters集合中,我有一些文档,其中包含来自另一个集合的文档的groups值ids.这就像引用另一个集合的FOREIGN键.
在另一个集合中,我们有与'_ids'对应的文档,这些文档存储在main parameters集合中.
以下是来自parameters集合的一个示例文档:
{
"_id" : ObjectId("538726134ba2222c0c0248b6"),
"name" : "Potta",
"groups" : [
"54c91b2c4ba222182e636943"
]
}
Run Code Online (Sandbox Code Playgroud)
我需要按组排序,但正如您在主要集合组中看到的,值是ID,但我想按组名排序.
这是一个来自groups集合的样本集合.
{
"_id" : ObjectId("54c91b2c4ba222182e636943"),
"name" : "Group 01",
}
Run Code Online (Sandbox Code Playgroud)
这可能在Mongo DB中实现吗?
谢谢
鉴于数据是
> db.parameters.find({})
{ "_id" : ObjectId("56cac0cd0b5a1ffab1bd6c12"), "name" : "potta", "groups" : [ "
123", "234" ] }
> db.groups.find({})
{ "_id" : "123", "name" : "Group01" }
{ "_id" : "234", "name" : "Group02" }
Run Code Online (Sandbox Code Playgroud)
在mongodb 3.2,您可以执行此操作$lookup以在同一数据库中执行左外部联接到未整数的集合,然后执行到sort下面的组名称.
> db.parameters.aggregate([
{$unwind: '$groups'},
{$lookup: {
from: 'groups',
localField: 'groups',
foreignField: '_id',
as: 'gr'}},
{$sort: {'gr.name': 1}}])
Run Code Online (Sandbox Code Playgroud)
对于under 3.2,请尝试执行以下操作
> var pa = db.parameters.find({});
> pa.forEach(function(doc) {
var ret = db.groups
.find({_id: {$in: doc.groups}})
.sort({name: 1});
ret.forEach(printjson)
});
Run Code Online (Sandbox Code Playgroud)
或者你可以通过mapReduce以下方式完成
// emit group id from parameters collection
> var map_param = function() {
var that = this;
this.groups.forEach(function(g){emit(that._id, g);})};
// emit group id and name from group collection
> var map_group = function() {emit(this._id, this.name);}
// combine those results from map functions above
> var r = function(k, v) {
var result = {id: '', name: ''};
v.forEach(function(val){
if (val.id !== null){ result.id = val;}
if (val.name !== null) {result.name = val;}
});
return result;};
> db.parameters.mapReduce(map_param, r, {out: {reduce: 'joined'}})
> db.groups.mapReduce(map_group, r, {out: {reduce: 'joined'}, sort: {name: 1}})
Run Code Online (Sandbox Code Playgroud)
最终,排序的结果在joined集合中.