skip to Main Content

I need to get total count of objects in the "photo" array field, and compare it to the value in "mls_media_count" field, so that I can detect when the values do not match.

    open_houses:null
    open_houses_lock:false
    photos:Array
         0:Object
         1:Object
         2:Object
         3:Object
         4:Object
         5:Object
         6:Object
         7:Object
         8:Object
         9:Object
     mls_media_count: 8

I have tried using $unwind, $project, $size, but haven’t had luck getting it to work.
Thanks in advance!

2

Answers


  1. Chosen as BEST ANSWER

    Thank you for response! This got me on right track and i ended up writing it like this:

        [{
     $match: {version: '5'
     }
    }, {
     $project: {
      item: -1,
      Photos: {
       $cond: {
        'if': {
         $isArray: '$photos'
        },
        then: {
         $size: '$photos'
        },
        'else': 'NA'
       }
      },
      mls_number: 1,
      mls_media_count: 1,
      'system.kw_photo_count': 1
     }
    }, {
     $match: {
      $expr: {
       $ne: [
        '$Photos',
        '$mls_media_count'
       ]
      }
     }
    }, {
     $count: 'list_id'
    }] 
    

  2. Query

    • $size can give the size of the array, and we can compare it with the media_count
    • first query keeps the documents where size is not correct
    • second query keeps the documents where size is correct

    Playmongo

    aggregate(
    [{"$match": 
       {"$expr": {"$ne": [{"$size": "$photos"}, "$mls_media_count"]}}}])
    

    Playmongo

    aggregate(
    [{"$match": 
       {"$expr": {"$eq": [{"$size": "$photos"}, "$mls_media_count"]}}}])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search