0

If I have a schema similar to the following:

{
    "_id" : "12345",
    "_class" : "Refrigerator",
    "items" : {
        "APPLE" : {
            "id" : 123,
            "name" : "APPLE"
        },
        "BANANA" : {
            "id" : 234,
            "name" : "BANANA"
        },
        "STRAWBERRY" : {
            "id" : 345,
            "name" : "STRAWBERRY"
        }
    },
},
{
    "_id" : "23456",
    "_class" : "Pantry",
    "items" : {
        "CEREAL" : {
            "id" : 456,
            "name" : "CEREAL"
        }
    },
}

I want to get a list of distinct items where the _class=Refrigerator. The result should be ["APPLE","BANANA","STRAWBERRY"]. How can I do this? Thank you!

1
  • It's better if you can store BSON in mongodb as { "items": [ { "id": 123, "name": "APPLE" }, { "id": 234, "name": "BANANA" }, { "id": 345, "name": "STRAWBERRY" } ] } Commented Apr 28, 2017 at 4:02

1 Answer 1

1

You can utilise aggregation operator $objectToArray (SERVER-23310) to turn keys into values. It should be able to group 'unknown' or 'dynamic' fields. This operator is available in MongoDB v3.4.4+

Given your example documents, you can use below aggregation pipeline

db.collection.aggregate([
    {$match:{"class":"Refrigerator"}}, 
    {$project:{"items":{$objectToArray:"$items"}}}, 
    {$unwind:"$items"}, 
    {$group:{_id:"$_id", result:{$addToSet:"$items.k"}}}
])

See also the manual for: $unwind, $group, and $addToSet

If applicable for your use case, I would recommend to re-consider your data schema for easier access to the information that you're after. MongoDB has a flexible schema, you should use this for your application benefits.

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.