0

I have a collection that looks something like the following (I have simplified it a lot). I need to query any record that doesn't have the same number of customersAccepted entries as customersInvited.

/* 1 */
{
    "_id" : ObjectId("5d7b8ab0f1e55a2e4b6ccfa2"),
    "title" : "Service AT19",
    "customersInvited" : [ 
        429409, 
        429410, 
        900
    ],
    "customersAccepted" : [ 
        429409, 
        429410, 
        900
    ],
    "groupId" : null,
    "deleted" : true,
    "deletedDate" : ISODate("2019-10-12T05:59:08.135Z"),
}

Is this possible with the $size operator? I'm familiar with it when looking for a fixed number, so my Plan B will be to add two separate fields called numAccepted and numInvited, then update that when the record is modified and do something like:

db.collection.find( { "numInvited": { $ne: "numAccepted" } } );

I'd really rather not maintain additional fields I don't need if it is possible to compare array size directly though. Any advice you can give on this would be greatly appreciated.

0

Is this possible with the $size operator? ... so my Plan B will be to add two separate fields called numAccepted and numInvited ...

The $size operator matches any array with the number of elements specified by the argument. In this case you have to compare the size of two array fields within the same document. You cannot use MongoDB Query Language (MQL) operators for this purpose.

The aggregation $size array operator returns the length of an array. To use aggregation operators within a find query, you have to use the $expr operator. Here is how it is done:

db.collection.find( { $expr: { $ne: [ { $size: "$customersInvited" }, { $size: "$customersAccepted" } ]  } } )

Note the $size and the $ne used in the above query are aggregation operators.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.