Home > Mobile >  Querying MongoDB array in Python returns not matched parts
Querying MongoDB array in Python returns not matched parts

Time:09-24

Having this simplified document:

{
   "_id" : "test_id",
   "name" : "customname",
   "timestamp" : "2010-10-10 10:00:01",
   "customarray" : [
       {
           "my_id" : 1,
           "value": 23
       },
       {
           "my_id" : 2,
           "value": 16
       }
   ]
}

I want to return just the customarray.value part for those documents which customarray.my_id = 1

This is my approach using pymongo:

res = [res for res in col.find({"customarray.my_id": 1}, {"customarray.value"})]

But I get this output:

{'_id': 'test_id', 'customarray': [{'value': 23}, {'value': 16}]}

When my desired output is:

{'_id': 'test_id', 'customarray': [{'value': 23}]}

How can I get only the desited value of the array? I dont want to get the second value (value = 16, which is my_id = 2)

Thanks in advance.

CodePudding user response:

You should make use of the $elemMatch operator inside the projection block and apply your filter conditions there instead.

res = [res for res in col.find({"customarray.my_id": 1}, { "name": 1, "customarray": { "$elemMatch": { "my_id": 1 } } })]

CodePudding user response:

You can try this aggregation query:

  • $unwind to deconstruct the array.
  • $match to get values you want.
  • $project to get the desired output.
db.collection.aggregate([
  {
    "$unwind": "$customarray"
  },
  {
    "$match": {
      "customarray.my_id": 1
    }
  },
  {
    "$project": {
      "_id": 0,
      "value": "$customarray.value"
    }
  }
])

Example here

  • Related