如何在Mongo中加入两个集合而无需查找 [英] How to join two collection in mongo without lookup

查看:91
本文介绍了如何在Mongo中加入两个集合而无需查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个收藏集,分别是帖子评论. 模型结构如下. 我想使用聚合查询帖子,并按长度总和之类的注释进行排序,目前,我可以在以下查询语句中查询长度总和之类的帖子注释.

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.

我的问题是如何在 Mongo 2.6版中查询帖子并加入评论集.我知道Mongo 3.2之后具有查找功能.

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.

我想查询帖子集并按喜欢的长度按外国评论进行排序.在mongo 2.6中是否有最好的方法?

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?

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

评论

/* 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"
    ]
}

查询诸如sum之类的帖子评论

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

推荐答案

没有最佳"查询方式,因为这实际上取决于您的特定需求,但是...您无法跨多个执行单个查询集合(如您所知,除了更高版本中的$lookup聚合管道功能之外).

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).

您需要进行多个查询:一个查询到post集合,一个查询到comment集合.

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).

这篇关于如何在Mongo中加入两个集合而无需查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆