0

I'm writing a code in which i find this kind of database (i'm using pymongo). How can i attribute these arrays inside the wishlist field to python arrays?

Alternatively, how can i search my database for a value inside an array inside the wishlist field. E.g.: i want to find all IDs that have, say, ["feldon","c15", "sp"] in their wishlists

{
    "_id" : "david",
    "password" : "azzzzzaa",
    "url" : "url3",
    "old_url" : "url3",
    "new_url" : ["url1", "url2"],
    "wishlist" : [
        ["all is dust", "mm4", "nm"],
        ["feldon", "c15", "sp"],
        ["feldon", "c15", "sp"],
        ["jenara", "shards", "nm"],
        ["rafiq", "shards", "nm"]
    ]
}

1 Answer 1

1

You can use distinct if elements in your sublist and are exactly in the same order.

db.collection.distinct("_id", {"wishlist": ["feldon", "c15", "sp"]})

If not, you need to use the aggregate method and the $redact operator.

db.collection.aggregate([
    {"$redact": {
        "$cond": [
            {"$setIsSubset": [
                [["feldon","c15", "sp"]], 
                "$wishlist"
            ]}, 
            "$$KEEP",
            "$$PRUNE"
        ]
    }}, 
    {"$group": {
        "_id": None, 
        "ids": {"$push": "$_id"}
    }}
])
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.