0

I want to help get mongodb one of several documents. I have the 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 to get as a result of a request of the Joint Document:

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

But I can not write a 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 to make a request?

alex10
  • 2,726
  • 3
  • 22
  • 35

2 Answers2

1

I got to join several documents with one query. Thanks to all, I got the answer to my 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 } }
])
alex10
  • 2,726
  • 3
  • 22
  • 35
0

As MonogoDB doesn't support Joins. There is no way you can get the desired output with a query.

If you need to implement a "self-join" when using MongoDB then you may have structured your schema incorrectly (or sub-optimally). In MongoDB (and noSQL in general) the schema structure should reflect the queries you will need to run against them.

In your specific case, I think you need to re-design your schema a little or do it on the client.

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

You can embed article in the user document. (If you think the total size of a document will not increase above 16 Mb).

Have a look at this answer for database design.

Community
  • 1
  • 1
thegreenogre
  • 1,559
  • 11
  • 22