ELel
ELel

Reputation: 37

check if a property contains a specific value in a document with pymongo

I have a collection of documents that looks like this

  {
    "_id": "4",
    "contacts": [
      {
        "email": "[email protected]",
        "name": "A1",
        "phone": "00",
        "crashNotificationEnabled": false,
        "locationShared": true,
        "creationDate": ISODate("2020-10-19T15:19:04.498Z")
      },
      {
        "email": "[email protected]",
        "name": "AG2",
        "phone": "00",
        "crashNotificationEnabled": false,
        "locationShared": false,
        "creationDate": ISODate("2020-10-19T15:19:04.498Z")
      }
    ],
    "creationDate": ISODate("2020-10-19T15:19:04.498Z"),
    "_class": ".model.UserContacts"
  }

And i would like to iterate through all documents to check if either crashNotificationEnabled or locationShared is true and add +1 to a counter if its the case, im quite new to python and mongosql so i actually have a hard time trying to do that, i tried a lot of things but there is my last try :

def users_with_guardian_angel(mongoclient):
try:
    mydb = mongoclient["main"]
    userContacts = mydb["userContacts"]
    users = userContacts.find()

    for user in users:
        result = userContacts.find_one({contacts : { $in: [true]}})
        if result:
            count_users = count_users + 1
    print(f"{count_users} have at least one notificiation enabled")

But the result variable stays empty all the time, so if somebody could help me to accomplish what i want to do and tell what i did wrong here ?

Thanks !

Upvotes: 0

Views: 367

Answers (1)

rickhg12hs
rickhg12hs

Reputation: 11942

Here's one way you could do it by letting the MongoDB server do all the work.

N.B.: This doesn't consider the possibility of multiple entries of the same user.

db.userContacts.aggregate([
  {
    "$unwind": "$contacts"
  },
  {
    "$match": {
      "$expr": {
        "$or": [
          "$contacts.crashNotificationEnabled",
          "$contacts.locationShared"
        ]
      }
    }
  },
  {
    "$count": "userCountWithNotificationsEnabled"
  }
])

Try it on mongoplayground.net.

Example output:

[
  {
    "userCountWithNotificationsEnabled": 436
  }
]

Upvotes: 1

Related Questions