MongoDb aggregation-framework,join不同的文档在同一个集合中

MongoDb aggregation-framework, join different documents are in the same collection

我想帮助获得 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  }
        }
    }
])

如何申请?

因为 MonogoDB 不支持 Joins。您无法通过查询获得所需的输出。

如果您在使用 MongoDB 时需要实施 "self-join",那么您的模式结构可能不正确(或次优)。在 MongoDB(和一般的 noSQL)中,模式结构应该反映您需要 运行 针对它们的查询。

在您的具体情况下,我认为您需要稍微重新设计您的架构或在客户端上重新设计。

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

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

看看这个 answer 数据库设计。

我必须通过一个查询来连接多个文档。 感谢大家,我得到了问题的答案。

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 } }
])