Question

I have documents like:

{
name: 'Nicholas',
friends : ['Amy', 'Joe', 'Amanda']
},
{
name: 'John',
friends : ['Amy', 'Amanda', 'Sam', 'Steve']
},

and I'd like to find all documents where 'Joe' is in the friends array.

In Mongo I guess this would be:

db.people.find({ 'friends' : { $elemMatch : 'Joe' } }

but how do I do this in Python with MongoKit:

connection.People.find( ?? )
Was it helpful?

Solution

Following answer is based on my test in mongo shell -

I just created a sample in my collection. Here is how you can search for the documents with "Joe" -

db.sample3.find({"friends":"Joe"})

output is { "_id" : ObjectId("5339c9ff0bb9bc1b3a5bf7a4"), "name" : "Nicholas", "friends" : [ "Amy", "Joe", "Amanda" ] }

For the query db.sample3.find({"friends":"Amy"}), output is -

{ "_id" : ObjectId("5339c9ff0bb9bc1b3a5bf7a4"), "name" : "Nicholas", "friends" : [ "Amy", "Joe", "Amanda" ] }
{ "_id" : ObjectId("5339ca120bb9bc1b3a5bf7a5"), "name" : "John", "friends" : [ "Amy", "Amanda", "Sam", "Steve" ] }

The query {"friends":"Joe"} works. So, you should be able to use the same in Mongokit. Here is the document I created -

db.sample3.find().pretty()
{
    "_id" : ObjectId("5339c9ff0bb9bc1b3a5bf7a4"),
    "name" : "Nicholas",
    "friends" : [
        "Amy",
        "Joe",
        "Amanda"
    ]
}
{
    "_id" : ObjectId("5339ca120bb9bc1b3a5bf7a5"),
    "name" : "John",
    "friends" : [
        "Amy",
        "Amanda",
        "Sam",
        "Steve"
    ]
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top