MongoDb aggregation-framework, join different documents are in the same collection -
i want mongodb 1 of several documents. have following data structure:
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" } ]) i want result of request of joint document:
{ _id:"123", blogs: {id:1, doc_type: "blogs", user: "gomer", article: "aaaa"}, user : {id:"gomer", doc_type: "user", group: ["user", "author"]} } but can not write valid request:
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 } } } ]) how make request?
i got join several documents 1 query. all, got answer question.
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 } } ])
Comments
Post a Comment