MongoDB: match non-empty doc in array

Viewed 29008

I have a collection structured thusly:

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

I need to find all documents that have at least one 'score' (element in score array) that has a certain value of 'bar' and a non-empty 'user' sub-document.

This is what I came up with (and it seemed like it should work):

db.col.find({score: {"$elemMatch": {bar:0, user: {"$not":{}} }}})

But, I get this error:

error: { "$err" : "$not cannot be empty", "code" : 13030 }

Any other way to do this?

5 Answers
 $group: {
        _id: '$_id',
        tasks: {
          $addToSet: {
            $cond: {
              if: {
                $eq: [
                  {
                    $ifNull: ['$tasks.id', ''],
                  },
                  '',
                ],
              },
              then: '$$REMOVE',
              else: {
                id: '$tasks.id',
                description: '$tasks.description',
                assignee: {
                  $cond: {
                    if: {
                      $eq: [
                        {
                          $ifNull: ['$tasks.assignee._id', ''],
                        },
                        '',
                      ],
                    },
                    then: undefined,
                    else: {
                      id: '$tasks.assignee._id',
                      name: '$tasks.assignee.name',
                    },
                  },
                },
              },
            },
          },
        },
Related