我想加入以下两个集合。 但是,这些集合是不同的数据库。
> use test
> db.payment_history.find()
{ "_id" : ObjectId("5752bbbaf12f5908ec24b3a9"), "user_id" : 1233, "cash_id" : 3 }
{ "_id" : ObjectId("5752bbbcf12f5908ec24b3aa"), "user_id" : 1233, "cash_id" : 1 }
{ "_id" : ObjectId("5752bba5f12f5908ec24b3a5"), "user_id" : 1234, "cash_id" : 1 }
{ "_id" : ObjectId("5752bbaaf12f5908ec24b3a6"), "user_id" : 1235, "cash_id" : 1 }
{ "_id" : ObjectId("5752bbaff12f5908ec24b3a7"), "user_id" : 1235, "cash_id" : 1 }
{ "_id" : ObjectId("5752bbb5f12f5908ec24b3a8"), "user_id" : 1236, "cash_id" : 3 }
> use test_mst
> db.mst_cash.find()
{ "_id" : ObjectId("5752bbebf12f5908ec24b3ab"), "cash_id" : 1, "num" : 100 }
{ "_id" : ObjectId("5752bbf1f12f5908ec24b3ac"), "cash_id" : 2, "num" : 200 }
{ "_id" : ObjectId("5752bbf8f12f5908ec24b3ad"), "cash_id" : 3, "num" : 500 }
{ "_id" : ObjectId("5752bbfff12f5908ec24b3ae"), "cash_id" : 4, "num" : 1000 }
我想输出如下所示的连接。 (关键键是cash_id)
{ "_id" : ObjectId("5752bbbaf12f5908ec24b3a9"), "user_id" : 1233, "cash_id" : 3, "num": 500 }
{ "_id" : ObjectId("5752bbbcf12f5908ec24b3aa"), "user_id" : 1233, "cash_id" : 1, "num": 100 }
{ "_id" : ObjectId("5752bba5f12f5908ec24b3a5"), "user_id" : 1234, "cash_id" : 1, "num": 100 }
{ "_id" : ObjectId("5752bbaaf12f5908ec24b3a6"), "user_id" : 1235, "cash_id" : 1, "num": 100 }
{ "_id" : ObjectId("5752bbaff12f5908ec24b3a7"), "user_id" : 1235, "cash_id" : 1, "num": 100 }
{ "_id" : ObjectId("5752bbb5f12f5908ec24b3a8"), "user_id" : 1236, "cash_id" : 3, "num": 500 }
我尝试编写如下的javascript。
> var map_1 = function(){ emit(this._id, {user_id: this.user_id, cash_id: this.cash_id}) };
> var map_2 = function(){ emit(this.cash_id, {num: this.num}) };
> var r = function(key, values){
var result = {"cash_id": 0};
values.forEach(function(v){
result.cash_id = v.cash_id;
});
return result;
};
> var r2 = function(key, values){
var result = {"num": 0};
values.forEach(function(v){
result.num = v.num;
});
return result;
};
> db.payment_history.mapReduce(map_1, r, {out: {reduce: 'joined'}});
> db.getSiblingDB('test_mst').mst_cash.mapReduce(map_2, r2, {out: {reduce: 'joined'}});
但是,加入collecion并不是mst_cash数据的合并结果。 我确保' db.getSiblingDB(' test_mst')。mst_cash.mapReduce(map_2,r2,{out:{reduce:'加入'}});&# 39;在test_mst数据库中创建join collecion。 我想将mst_cash数据合并到测试数据库中的join collecion中。 我该怎么办?
答案 0 :(得分:0)
首先 - mongo不提供不同数据库的操作。
要 加入 集合,它们必须是同一个数据库,然后我们可以使用汇总框架,如下面的代码段:
var lookUp = {
$lookup : {
from : "mst_cash",
localField : "cash_id",
foreignField : "cash_id",
as : "operations"
}
}
var unwind = {
$unwind : "$operations"
}
var project = {
$project : {
_id : 1,
"user_id" : 1,
"cash_id" : 1,
"num" : "$operations.num"
}
}
db.payment_history.aggregate([lookUp, unwind, project])
该查询的结果是:
{
"_id" : ObjectId("5752bbbaf12f5908ec24b3a9"),
"user_id" : 1233.0,
"cash_id" : 3.0,
"num" : 500.0
}