MongoDB: match non-empty doc in array

后端 未结 4 1422
半阙折子戏
半阙折子戏 2021-02-02 07:46

I have a collection structured thusly:

{
  _id: 1,
  score: [
    {
      foo: \'a\',
      bar: 0,
      user: {user1: 0, user2: 7}
    }
  ]
}
<
4条回答
  •  孤街浪徒
    2021-02-02 08:08

    You probably want to add an auxiliary array that keeps track of the users in the user document:

    {
      _id: 1,
      score: [
        {
          foo: 'a',
          bar: 0,
          users: ["user1", "user2"],
          user: {user1: 0, user2: 7}
        }
      ]
    }
    

    Then you can add new users atomically:

    > db.test.update({_id: 1, score: { $elemMatch: {bar: 0}}},                       
    ... {$set: {'score.$.user.user3': 10}, $addToSet: {'score.$.users': "user3"}})
    

    Remove users:

    > db.test.update({_id: 1, score: { $elemMatch: {bar: 0}}},
    ... {$unset: {'score.$.user.user3': 1}, $pop: {'score.$.users': "user3"}})      
    

    Query scores:

    > db.test.find({_id: 1, score: {$elemMatch: {bar: 0, users: {$not: {$size: 0}}}}})
    

    If you know you'll only be adding non-existent users and removing existent users from the user document, you can simplify users to a counter instead of an array, but the above is more resilient.

提交回复
热议问题