Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

mongodb - mongo count rows from an array of provided data

I have collection like this:

{ 
   "_id" : ObjectId("4d663451d1e7242c4b68e000"), 
  "topic" : "abc", 
  "subLevel" : {
     "id" : 1
  }
}
{ 
    "_id" : ObjectId("4d6634514cb5cb2c4b69e000"), 
    "topic" : "bce", 
    "subLevel" : {
        "id" : 1
     }
}

{ 
    "_id" : ObjectId("4d6634514cb5cb2c4b70e000"), 
    "topic" : "bec", 
    "subLevel" : {
        "id" : 2
     }
}
{ 
    "_id" : ObjectId("4d6634514cb5cb2c4b70e000"), 
    "topic" : "vvv", 
    "subLevel" : {
        "id" : 3
     }
}

and I need to count how many documents exist for provided subLevel.id list, for example if I provide 1 and 2 it should show me that for 1 we have 2 documents and for 2 only 1 document and simply omit document where subLevel.id is 3 as it's not in the list of id's.

I tried to do it with a aggregate

db.getCollection('products').aggregate( [
   { $project: 
       {  "has_sublevel" : {$in: [ "subLevel.id", [1 , 2 ]]} }
   },
   { $group: { _id : "$subLevel.id", count: { $sum: 1 } } }
] )

but result is

{
   _id : null,
   count: 4
}

how can I do it, thanks in advance!

If transform it to SQL which I familiar more, query should look like this:

select subLevelId, count(id) FROM products where subLevelId in (1,2) group by subLevelId

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I've understand correctly, you are so so close, check this query:

  • First use $match to get only documents whose subLevel.id is 1 or 2.
  • Then, as you have done, $group by the id and sum to get total count:
db.collection.aggregate([
  {
    "$match": { "subLevel.id": { "$in": [ 1, 2 ] } }
  },
  {
    "$group": { "_id": "$subLevel.id", "count": { "$sum": 1 } }
  }
])

Example here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...