1

I have a user collection, and each user has different number of id_cards, all id_cards are stored in an array, I can get all users that have 7 id_card by using array $size operator, how do I get the users with say more then 5 id_cards?

5
  • 1
    You will have to use aggregation framework. Refer docs.mongodb.org/v3.0/reference/operator/aggregation/size
    – harshavmb
    Commented Dec 19, 2015 at 9:21
  • Use $gt or $lt based on your requirement
    – harshavmb
    Commented Dec 19, 2015 at 9:22
  • it doesn't work Commented Dec 21, 2015 at 9:48
  • can you paste the query you used?
    – harshavmb
    Commented Dec 21, 2015 at 13:45
  • 1
    You cannot use $size operator used with find queries. This operator accepts a number for comparison, so an equality comparison works fine (as you had mentioned "... I can get all users that have 7 id_card by using array $size operator..." . But, you cannot specify range operators like $gt. "...how do I get the users with say more then 5 id_cards?" - for this you can use an aggregation query where there is a $size aggregation array operator which returns the size of an array. This value can be compared with a number using any of the operators, like $eq, $gt, etc.
    – prasad_
    Commented May 7 at 3:58

1 Answer 1

0

Let's say you have a collection users with documents like

{
   _id: "5ffb5796-15d3-4ad4-b40a-6de7a12cb057",
   user_name: "Leeloo Dallas",
   id_cards: [
      {
         card_nr: "G476553G",
         type: "Multipass"
      },
      {
         ...
      }
   ]
} 

You could then query

db.users.find({"id_cards.4": {$exists: true}})

This matches all documents where the id_cards array entry with index 4 exists. Index 4 of course being the 5th element. In other words, this returns all users with 5 or more ID cards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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