Mongodb find a document with all subdocuments satisfying a condition

前端 未结 3 1125
时光说笑
时光说笑 2020-12-11 03:30

I have Game collection in my DB:

var game = {
  players: [{username:\"user1\", status:\"played\"},
            {username:\"user2\", status:\"accepted\"}]
}
<         


        
3条回答
  •  时光说笑
    2020-12-11 03:58

    I ran into this problem too. I was trying to use $all and making little to no progress. It helped to flip my perspective on the problem and use $not instead. I wrote about what I found here.

    In your situation, you should be able to do something like this:

    db.games.find({
      players: {
        $not: {
          $elemMatch: {
            status: { $ne: "played" }
          }
        }
      }
    })
    

    Find all documents with a player status not equal to "played" and return the inverse of that set. The nice thing about this is that you never have to worry about adding more status values.

提交回复
热议问题