2015-05-11 41 views
0

我想帮助获得mongodb几个文档之一。 我有以下数据结构:MongoDb聚合框架,加入不同的文档在同一集合

db.coll.insert([ 
{_id: "gomer", doc_type: "user", group: ["user", "author"] }, 
{_id: "dante", doc_type: "user", group: ["user"] }, 
{_id: 1, doc_type: "blogs", user: "gomer", article: "aaaa" }, 
{_id: 2, doc_type: "blogs", user: "vasya", article: "bbbb" } 
]) 

我想作为共同文件的请求的结果:

{ _id:"123", 
    blogs: {id:1, doc_type: "blogs", user: "gomer", article: "aaaa"}, 
    user : {id:"gomer", doc_type: "user", group: ["user", "author"]} 
} 

但我不能写一个有效的请求:

db.coll.aggregate([ 
    { $match: {$or:[{doc_type:"blogs"},{doc_type:"user"}]} }, 
    { $project: { 
     blogs: { id:$id, doc_type:"blogs", user:$user, article:$article }, 
     user: { id:$id, doc_type:"user", group:$group } 
     } 
    } 
]) 

如何提出请求?

回答

1

我用一个查询加入了多个文档。 感谢所有人,我得到了我的问题的答案。

db.test.aggregate([ 
    { $match: { $or: [ {doc_type: "blogs"}, {doc_type: "user"} ] } }, 
    { $project: { 
      a: 1, 
      blogs: { 
       $cond: { 
        if: { doc_type: '$blogs'}, 
        then: {_id:"$_id", user:"$user", article:"$article"}, 
        else: null 
       } 
      }, 
      user: { 
       $cond: { 
        if: { doc_type: '$user' }, 
        then: { _id:"$_id", group:"$group"}, 
        else: null 
       } 
      } 
     } 
    }, 
    { $group : { 
       _id : { a: "$a" }, 
       user: { $push: "$user" }, 
       blog: { $push: "$blogs" }, 
      } 
    }, 
    { $unwind : "$blog" }, 
    { $unwind : "$user" }, 
    { $project:{ 
     user: "$user", 
     article: "$blog", 
     matches: { $eq:[ "$user._id", "$blog.user" ] } } 
    }, 
    { $match: { matches: true } } 
]) 
0

由于MonogoDB不支持Joins。您无法通过查询获取所需的输出。

如果您在使用MongoDB时需要实现“自连接”,那么您可能会错误地(或次优)地构建您的架构。在MongoDB中(和一般的noSQL),模式结构应该反映出你需要运行的查询。

在您的具体情况下,我认为您需要稍微重新设计您的模式,或者在客户端上进行。

{_id: "gomer", doc_type: "user", group: ["user", "author"], article:["aaaa"]}, 

您可以在用户文档中嵌入article。 (如果您认为文档的总大小不会超过16 Mb)。

查看此answer数据库设计。