2

How would we go about finding records where multiple conditions are true within the same sub-document while at least one of these conditions is negated?

db.getCollection('clients').find( { 
    data: { '$exists': true },
    'data.updates': { '$elemMatch': { 
        name: { $not: /^KB3109103/i }, 
        install_date: { $gt: 128573812 } 
    } } 
});

This returns all records because $not doesn't seem to work inside $elemMatch.

Solution:

Found a work around, adding $and (which according to the documentation is the same as without) solved it.

db.getCollection('clients').find( { 
    data: { '$exists': true },
    'data.updates': { '$elemMatch': { 
        $and: [
            {name: { $not: /^KB3109103/i }}, 
            {install_date: { $gt: 128573812 }}
        ]
    } } 
});
Community
  • 1
  • 1
user2693017
  • 1,750
  • 6
  • 24
  • 50
  • 1
    Could you show with some sample documents and the output what you want to achieve. – Ashh Dec 30 '18 at 06:50
  • I want to find documents where at least one sub-document (within an array of sub-documents) matches multiple conditions, this works fine with `elemMatch` as long as there is no negation. – user2693017 Dec 30 '18 at 07:03
  • @AnthonyWinzlet https://mongoplayground.net/p/qNa-AcSE4u3 – user2693017 Dec 30 '18 at 07:18
  • Possible dupe of https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection ? – Ashh Dec 30 '18 at 07:34
  • @AnthonyWinzlet nah, its not about the amount of sub documents it returns. I don't care about these. I only need the count of top level documents. – user2693017 Dec 30 '18 at 07:39
  • @AnthonyWinzlet I need to negate inside the sub-document not outside – user2693017 Dec 30 '18 at 08:29
  • Found a work around, adding $and (which according to the documentation is the same as without) solved it. – user2693017 Dec 30 '18 at 09:32

0 Answers0