Sfinos
Sfinos

Reputation: 379

MongoDB Query in Pymongo

I have a collection in this format:

{
"name": ....,
"users": [....,....,....,....]
}

I have two different names and I want to find the total number of users that belongs to both documents. Now, I am doing it with Python. I download the document of name 1 and the document of name 2 and check how many users are in both of the documents. I was wondering if there is any other way to do it only with MongoDB and return the number.

Example:

{
"name": "John",
"users": ["001","003","008","010"]
}

{
"name": "Peter",
"users": ["002, "003", "004","005","006","008"]
}

The result would be 2 since users 003 and 008 belongs to both documents.

How I do it:

doc1 = db.collection.find_one({"name":"John"})
doc2 = db.collection.find_one({"name":"Peter"})

total = 0
for user in doc1["users"]:
    if user in doc2["users"]:
       total += 1

Upvotes: 0

Views: 148

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151170

You could also do this with the aggregation framework, but I think it would only make sense if you were doing this over a more than two users even though your could use it that way:

db.users.aggregate([
    { "$match": {
         "name": { "$in": [ "John", "Peter" ] }
    }},

    { "$unwind": "$users" },
    { "$group": {
        "_id": "$users",
        "count": { "$sum": 1 }
    }},
    { "$match": { "count": { "$gt": 1 } }},
    { "$group": {
        "_id": null,
        "count": { "$sum": 1 }
    }}
])

That allows you to find the same counts over the names you supply to $in in $match

Upvotes: 1

Related Questions