数不胜于评论

时间:2013-01-28 18:46:01

标签: mongodb

collection Status:
    [
        {   
            _id: '1',
            StatusName: '....', 
            Comments: [
                        {
                            id_: '2',
                            CommentName: '.....',
                            Likes: ['user1', 'user2', 'user3']
                        },
                        {
                            id_: '3',
                            CommentName: '.....',
                            Likes: ['user2', 'user3']
                        }
                    ]
        },
        {   
            _id: '3',
            StatusName: '....', 
            Comments: [
                        {
                            id_: '4',
                            CommentName: '.....',
                            Likes: ['user1', 'user2', 'user3', 'user4']
                        },
                        {
                            id_: '5',
                            CommentName: '.....',
                            Likes: ['user1', 'user3']
                        }
                    ]
        }

    ]

我想要评估评论_id ='2'和状态_id:'1'

1 个答案:

答案 0 :(得分:1)

一种方法是使用聚合框架:

db.status.aggregate(
[
  {$match : {_id : "1", }}, 
  {$unwind: "$Comments"}, 
  {$match: {"Comments.id_": "2"}},
  {$unwind: "$Comments.Likes"},
  {$group: {_id: {"statusId":"$_id","CommentId":"$Comments.id_"}, 
            "likes": {$sum:1}}
  }
] )