mongodb - mongodb - How to join two collection in mongo without lookup - answerstu - answerstu.com answerstu

mongodb - How to join two collection in mongo without lookup

I have two collection, there name are post and comment. The model structure is in the following. I want to use aggregation query post and sort by comments like length sum, currently I can query a post comments like length sum in the following query statement.

My question is how can I query post and join comment collection in Mongo version 2.6. I know after Mongo 3.2 have a lookup function.

I want to query post collection and sort by foreign comments likes length. Is it have a best way to do this in mongo 2.6?

post

{
    "_id": ObjectId("5a39e22c27308912334b4567"),
    "uid": "0",
    "content": "what is hello world mean?",
}

comment

/* 1 */
{
    "_id": ObjectId("5a595d8c2703892c3d8b4567"),
    "uid": "1",
    "post_id": "5a39e22c27308912334b4567",
    "comment": "hello world",
    "like": [
        "2"
    ]
}
/* 2 */
{
    "_id": ObjectId("5a595d8c2703892c3d8b4512"),
    "uid": "2",
    "post_id": "5a39e22c27308912334b4567",
    "comment": "hello stackoverflow",
    "like": [
        "1",
        "2"
    ]
}

Query a post comments like sum

db.getCollection('comment').aggregate([
    {
        "$match": {
            post_id: "5a39e22c27308912334b4567"
        }
    },
    {
        "$project": {
            "likeLength": {
                "$size": "$like"
            },
            "post_id": "$post_id"
        }
    },
    {
        "$group": {
            _id: "$post_id",
            "likeLengthSum": {
                "$sum": "$likeLength"
            }
        }
    }
])

1 Answer

  1. Edwin- Reply

    2019-11-13

    There is no "best" way to query, as it'll really depend on your specific needs, but... you cannot perform a single query across multiple collections (aside from the $lookup aggregation pipeline function in later versions, as you already are aware).

    You'll need to make multiple queries: one to your post collection, and one to your comment collection.

    If you must perform a single query, then consider storing both types of documents in a single collection (with some identifier property to let you filter on either posts or comments, within your query).

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>