mongoDB distinct & where in same query?

前端 未结 3 1114
無奈伤痛
無奈伤痛 2020-12-08 00:29

Let\'s say I have the following documents

Article { Comment: embedMany }

Comment { Reply: embedMany }

Reply { email: string, ip: string }

相关标签:
3条回答
  • 2020-12-08 00:35
    distinctdates=db.dailyreport_detailed.find(
    
    {'uid':personemail,'month':searchdate2,'year':searchdate1}
    )
    
    .distinct('date_only')
    

    where find will retrieve as per condition and distinct at the end will give unique dates.

    0 讨论(0)
  • 2020-12-08 00:38

    Distinct query in mongo with condition works like this

     db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"})
    

    not other way around

    EDIT:

    I understand the problem now, inorder to match/filter subdocuments we need to use $elemMatch operator, like this

      db.Article.distinct("Comment.Reply.ip",{Comment: {$elemMatch: {"Reply.email" : "xxx"}}})
    

    but this will not work if the sub-document contains sub arrays (in your case, you have array of replies). There is an existing issue $elemMatch on subArray is opened. And its planned for mongo 2.1. You can check out the link for more info

    0 讨论(0)
  • 2020-12-08 00:45

    Maybe you could try this

    db.Article.aggregate([
    {$unwind: "$Comment"},
    {$unwind: "$Comment.Reply"},
    {$match: {"Comment.Reply.email": "xxx"}},
    {$group: {_id: "$Comment.Reply.ip"}}
    ])
    

    The result of example should be

    /* 1 */
    {
        "_id" : "192.168.1.1"
    }
    
    /* 2 */
    {
        "_id" : "128.168.1.1"
    }
    
    0 讨论(0)
提交回复
热议问题