MPA
MPA

Reputation: 1117

Pymongo - Query mongdb for first array elemnet by query of list of values

Given collection:

{
    "_id" : "1.1000038",
    "recomendation" : [ 
        "1.6739718"
    ]
}

/* 2 */
{
    "_id" : "1.1000069",
    "recomendation" : [ 
        "1.9185509", 
        "1.9051998", 
        "1.9034279", 
        "1.8288046", 
        "1.8152670", 
        "1.858775", 
        "1.6224229", 
        "1.4591674", 
        "1.3862464", 
        "1.3427739", 
        "1.3080062", 
        "1.3003608", 
        "1.1694619", 
        "1.1634683", 
        "1.1590664", 
        "1.1524146", 
        "1.754599", 
        "1.700837", 
        "1.763617"
    ]
}

I need to query the MongoDB for a list of values and get the first element of the list of values

here is the query by mongo syntax

db.getCollection('similar_articles').find({"_id":{$in:["1.1000069","1.1000038"]}})

I don't want to filter it on the python side because it's can be too big.

I didn't find any documentation on it

desire output: Pandas DataFrame

_id         recom 
1.1000038   1.6739718
1.1000069   1.9185509

Upvotes: 0

Views: 196

Answers (1)

J.F.
J.F.

Reputation: 15235

I don't know pymongo so well, but you need this query:

First $match by _ids into the arreay (this is like the find you have).

And later use $project to create the field recom (you can use "recomendation" to overwrite the existing field) and set the value as the first into the array.

db.collection.aggregate([
  {
    "$match": { "_id": { "$in": [ "1.1000069", "1.1000038" ] } }
  },
  {
    "$project": { "recom": { "$arrayElemAt": [ "$recomendation", 0 ] } }
  }
])

Example here

Looking the doumentation it seems you only need to copy and paste this query.

Upvotes: 1

Related Questions