Thomas Wagenaar
Thomas Wagenaar

Reputation: 6759

MongoDB find documents which have multiple keys in a field

This is how a documents looks like in my dataset:

{
  username: 'stack',
  attempts: { 1517761701: false, 1512341532: true }
}

{
  username: 'overflow',
  attempts: { 1217563721: false }
}

Now, I want to retrieve every document in my dataset where attempts contains more than óne key. So the query should return the document of user 'stack' but not of user 'overflow'. What query can I apply here?

Upvotes: 1

Views: 661

Answers (3)

Saravana
Saravana

Reputation: 12817

try $objectToArray to convert object to array and count the number of keys if you are using mongo 3.6+

db.cols.aggregate(
  [
    {$addFields: {count : {$size : {$ifNull : [{$objectToArray : "$attempts"}, []]}}}},
    {$match: {count : {$gt : 1}}},
    {$project: {count : 0}}
  ]
)

Upvotes: 1

user9251303
user9251303

Reputation:

Convert attempts to an array, $unwind and then use $sortByCount to do all the work..

db.collection_name.aggregate( [ 
{ $addFields : { array : { $objectToArray : "$attempts"} } },
{ $unwind : "$array" },  
{ $sortByCount : "$username" },
{ $match : { count : { $gte : 2 } } }
])

Outputs:

{
    "_id" : "stack",
    "count" : 2
}

Upvotes: 0

chridam
chridam

Reputation: 103365

Use $redact for a single pipeline:

db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                {
                    "$gt": [
                        { "$size": { 
                            "$objectToArray": {
                                "$ifNull": [
                                    "$attempts",
                                    { }
                                ]
                            }
                        } },
                        1
                    ]
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

Upvotes: 0

Related Questions