1

I have stored values in multiple variables. below are the input variables.

uid = Objectid("5d518caed55bc00001d235c1")
disuid = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']

These values are changed dynamically. and below is my code:

user_posts.aggregate([{
    "$match": {
        "$or": [{ "userid": uid }, {
            "userid": {
                "$eq":
                    disuid
            }
        }]
    }
},
{
    "$lookup": {
        "from": "user_profile",
        "localField": "userid",
        "foreignField": "_id",
        "as": "details"
    }
},
{ "$unwind": "$details" },
{
    "$sort": { "created_ts": -1 }
},
{
    "$project": {
        "userid": 1,
        "type": 1,
        "location": 1,
        "caption": 1
    }
}
])

In the above code, I am getting matched uid values only but I need documents matched to disuid also.

In userid field, we have stored "Objectid" values only. So my concern is how to add "Objectid" to "disuid" variable and how to write match condition for both variables using userid field?

1 Answer 1

1

Ok you can do it in two ways :

As you've this :

uid = Objectid("5d518caed55bc00001d235c1")
disuid = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']

You need to convert your list of strings to list of ObjectId's using python code :

from bson.objectid import ObjectId


disuid = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']
my_list = []


for i in disuid:
    my_list.append(ObjectId(i))

It will look like this : [ObjectId('5d76b2c847c8d3000184a090'),ObjectId('5d7abb7a97a90b0001326010')]

then by using new list my_list, you can do query like this :

user_posts.aggregate([{"$match" : { "$or" : [{ "userid" : uid }, { "userid" : { "$in" : my_list }}]}}])

Or in the other way which I wouldn't prefer, as converting just few in code is easier compared to n num of values for userid field over all documents in DB, but just in case if you want it to be done using DB query :

user_posts.aggregate([{$addFields : {userStrings : {$toString: '$userid'}}},{"$match" : { "$or" : [{ "userid" : uid }, { "userStrings" : { "$in" : disuid }}]}}])

Note : In case if you don't have bson package, then you need to install it by doing something like pip install bson

Sign up to request clarification or add additional context in comments.

2 Comments

Bro can you please help with the solution. please find the below link stackoverflow.com/questions/58573157/…
@RameshReddy : Sorry I'm a bit completely busy with my stuff, Please check my answer !!

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.