-6
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']
                        }
                    ]
        }

    ]

I want count Like of Comment _id = '2' and Status _id: '1'

4

1 回答 1

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}}
  }
] )
于 2013-01-29T06:19:15.460 回答