如何从mongodb中的多个集合中选择数据?

时间:2016-07-05 13:29:49

标签: mongodb mongodb-query

我创建了三个集合,一个用于用户详细信息,第二个用于帖子,第三个用于喜欢和评论。如果已经,我想要访问具有其他集合的喜欢的帖子的帖子等。我设计了下面的文档,我想访问结果。这样做的最佳方式是什么,或者我的设计很糟糕。请帮助。

发布数据

{
    "_id" : ObjectId("57500dfbba3dfb0cd0ec02c1"),
    "post" : {
        "fileLocation" : "uri/mediaServer/position",
        "timestamp" : "Jun 2, 2016 4:14:11 PM",
        "title" : "selling grocery",
        "description" : "abc def ghe",
        "userID" : "abc",
        "userIP" : "192.168.1.22",
        "category" : 2
    },
    "price" : 324.17
}

用户数据

{
    "_id" : ObjectId("57644c80a4b3681550aa6ba9"),
    "userId" : "abc",
    "userName" : "abcdef12",
    "email" : "xyz@gmail.com",
    "phone" : "78654321011",
    "password" : "12345678",
    "imageEncoded" : "gfwyegyivyggiyekwacktfuitbcliupouygfYYU",
    "profession" : "developer",
    "about" : "working at google ",
    "married" : false,
    "gender" : "m",
    "interests" : [ 
        "chess", 
        "hollowood movies", 
        "listening music"
    ],
    "skills" : [ 
        "core java", 
        "android", 
        "programing in c"
    ],
    "registrationIp" : "192.168.1.9",
    "loginAttempts" : 0,
    "address" : {
        "houseNumber" : "f12",
        "societyId" : "hr_far_sec15A_0032"
    },
    "creationDate" : ISODate("2016-06-17T19:16:16.283Z"),
    "ActiveSessionsIds" : [ 
        "id1"
    ]
}

喜欢和评论数据

{
    "_id" : ObjectId("57500dfbba3dfb0cd0ec02c1"),
    "comments" : [ 
        {
            "author" : {
                "UserId" : "abc",
                "authorName" : "abcdef12"
            },
            "comment" : "i want to buy it",
            "date" : "Jul 4, 2016 3:55:48 PM",
            "commentId" : "577a39ad670f1319986001e8"
        }
    ],
    "userId" : [ 
             "abc"
      ],
    "counter_like" : 1
    "counter_comment" : 1
}

我的查询查询是:

db.posts_collection.aggregate([

    { 
       $lookup:{
               from:"postmetadatacollection",
               localField:"_id",
               foreignField:"_id",
               as:"Data"
              }
    },
    {
       $lookup: {
                from: "user_profiles", 
                localField: "post.userID",
                foreignField: "userId",
                as: "user"
            }
    },
    {  
        $project: {
            "_id":0,
            "post.timestamp":1,
            "post.category":1,
            "post.userID":1,
            "post.description":1,
            "post.title":1,
            "CommentCount":"$Data.counter_comment",
            "LikeCount":"$Data.counter_like",
            "userName":"$user.userName",
            "price":1,
    "startDate":1,
    "endDate":1,
    "workingDays":1,
    "fees":1,
    "location":1,
    "":1,
            }
    }

如果特定userId存在于userId []集合中,或者是否有注释数据,那么我想在每个帖子中获得true / false,完整的$ lookUp 例如:喜欢userId:abc,如果它喜欢帖子或者不喜欢聚合输出中的每个帖子

0 个答案:

没有答案