Search code examples
mongodbfindcursor

get data from mongodb in match condition


I have data.
condition is: valid home count > 0 (valid home means deleted not true)

{
    "_id": 998e58,
  "home": [
    {
     "home_id": 433667,
     "deleted": true
    },
    {
     "home_id": 488742,
     "deleted": ""
    },
    {
     "home_id": 479331,
     "deleted": true
    },
    {
     "home_id": 481125,
    },
 ]
},
{
    "_id": 889g45,
  "home": [
    {
     "home_id": 934456,
     "deleted": true
    },
    {
     "home_id": 978646,
     "deleted": true
    },
 ]
},

because:
"_id": 998e58, it's total home count = 4, not valid home = 2, so valid home count is 4-2 = 2, it bigger than 0. --> match
"_id": 889g45, it's total home count = 2, not valid home = 2, so valid home count is 2-2 = 0, it equal 0. --> not match

so, if data match condition(means valid home count >0).
How can I use mongodb condtion to achieve my goal?
BTW, The number of my device may be tens of thousands, therefore if use unwind, groupby...
It may exceed the memory limit. ORZ.

I hope when I write command: db.colletion_name.find(...),
I will get data:

{
    "_id": 998e58,
  "home": [
    {
     "home_id": 488742,
     "deleted": ""
    },
    {
     "home_id": 481125,
    },
 ]
}

Solution

  • first we use filter to find all elements that deleted is not true

    then we addFields to add size of newHome array as number

    and after that we match doc with size > 0

    and then project to create expected output

    db.collection_name.aggregate([
          {
              $project:{
                  newHome:{
                  $filter :{
                      input:"$home",
                      as:"z",
                      cond:{$ne:["$$z.deleted",true]}
                  }
              }
            }
          },
          {
              $addFields:{
                  numOfActive : {$size:"$newHome"}
              }
          },
          {
              $match:{numOfActive:{$gt:0}}
          },
          {project:{
              _id:1,
              home:"$newHome"
          }}
      ])