MongoDB group with multiple id
mongodb, nosql, python
Solution
Query:
db.collection.aggregate([{
$match: {
type: {
"$exists": true
},
location: {
"$exists": true
},
language: {
"$exists": true
}
}
}])
Problem
I have a set of documents with more than 20 keys in each of them, and the keys vary with documents. Some keys may not be present in all the documents. I am trying to run a MongoDB group operation using the aggregation framework. The query looks something like this - ``` db.collection.aggregate([{'$group': {'count': {'$sum': 1}, '_id': {'location': '$location', 'type': '$type', 'language': '$language'}}}]) ``` In ideal case, it should return the documents where 3 of the keys should be present and perform a "group-by" operation on them. But the result looks something like this - ``` { "result" : [ { "_id" : { "location" : "abc", "type" : "456" }, "count" : 5 }, { "_id" : { "type" : "123", "language" : "english" }, "count" : 1 }, { "_id" : { "location" : "ghi", "type" : "9876", "language" : "latin" }, "count" : 2 }, { "_id" : { "language" : "hebrew", "type" : "9434" }, "count" : 3 }, { "_id" : { "type" : "525", "location" : "cari" }, "count" : 1 }, { "_id" : { "language" : "spanish", "location" : "dff" }, "count" : 12 }, { "_id" : { "location" : "adpj", "type" : "3463", "language": "english" }, "count" : 8 }, { "_id" : { "language" : "french", "location" : "nts" }, "count" : 6 } ], "ok" : 1 } ``` The problem is, MongoDB does the group operation even when it does not find all 3 keys I asked for in the query and shows partial group by. I am only interested in the results where I get all the keys. Filtering in the client side is not an option. Can anyone help out?