1

I'm trying to scrape a database of information, but was having trouble querying. Here's the basic database setup in MongoDB:

{
  "ID": 346,
  "data": [
    {
      "number": "23",
      "name": "Winnie"
    },
    {
      "number": "12",
      "name": "Finn"
    },
    {
      "number": "99",
      "name": "Todd"
    }
  ]
}


{
  "ID": 346,
  "data": [
    {
      "number": "12",
      "name": "Ram"
    },
    {
      "number": "34",
      "name": "Greg"
    },
    {
      "number": "155",
      "name": "Arnie"
    }
  ]
}

relevant Python code is below:

import pymongo
import json
import io
import sys
from bson.json_util import dumps
from pymongo import MongoClient
stringArr = ['"23"', '"12"', '"155"']
for x in range(0, len(stringArr))
print(collection.find({"data.number" :  stringArr[x]}).count())

When I enter collection.find({"data.number" : "23"}).count() I return the correct number of entries that have "23" as the number in data, so I presume my syntax for find in Python to be messed up, likely having to do with the variable being a string, but I'm fairly inexperienced with MongoDB, let alone PyMongo. Any suggestion would be greatly appreciated!

2
  • 2
    why do you have '"155"' why not just '155'? Commented Jun 13, 2017 at 18:56
  • this worked, thanks!!!! Commented Jun 13, 2017 at 19:07

1 Answer 1

1

$elemMatch operator is used to match values contained within an array field belonging to BSON document.

According to description as mentioned in above question please try executing following raw query in MongoDB shell.

    db.collection.find({
    data: {
        $elemMatch: {
            number: {
                $in: ["23", "12", "155"]
            }
        }
    }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.