Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

database - Count array elements that matches condition

I have a mongoDB collection called "conference" with an array of participants as below :

[
  {
    "_id" : 5b894357a0c84d5a5d221f25, 
    "conferenceName" : "myFirstConference",
    "startDate" : 1535722327, 
    "endDate" : 1535722420,
    "participants" : [
        {
            "name" : "user1", 
            "origin" : "internal", 
            "ip" : "192.168.0.2"
        },
        {
            "name" : "user2", 
            "origin" : "external", 
            "ip" : "172.20.0.3"
        }, 
    ]
  },
  ...
]

I would like to get the following result :

[
  {
     "conferenceName" : "myFirstConference",
     "startDate" : 1535722327, 
     "endDate" : 1535722420,
     "internalUsersCount" : 1
     "externalUsersCount" : 1,
  },
  ...
]

I tried the request below but it's not working :

db.getCollection("conference").aggregate([
   {
     $addFields: {
       internalUsersCount : {
            $size : { "$participants" : {$elemMatch : { origin : "internal" }}}
         },
       externalUsersCount : {
            $size : { "$participants" : {$elemMatch : { origin : "external" }}}
         }         
     }
   }
])

How is it possible to count "participant" array elements that match {"origin" : "internal"} and {"origin" : "external"} ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use $filter aggregation to filter out the external origin and internal origin along with the $size aggregation to calculate the length of the arrays.

Something like this

db.collection.aggregate([
  { "$addFields": {
    "internalUsersCount": {
      "$size": {
        "$filter": {
          "input": "$participants",
          "as": "part",
          "cond": { "$eq": ["$$part.origin", "internal"]}
        }
      }
    },
    "externalUsersCount": {
      "$size": {
        "$filter": {
          "input": "$participants",
          "as": "part",
          "cond": { "$eq": ["$$part.origin", "external"] }
        }
      }
    }
  }}
])

Output

[
  {
    "conferenceName": "myFirstConference",
    "endDate": 1535722420,
    "externalUsersCount": 1,
    "internalUsersCount": 1,
    "startDate": 1535722327
  }
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...