Reputation: 55
The question might be worded improperly, but this is my problem. I have a MySQL query that finds which user has checked out the most books from a library. The SQL query works just fine, but I am brand spankin' new to the MongoDB world. Here's my SQL query:
SELECT UID, count(UID)
FROM checkout_data
GROUP BY UID
ORDER BY count(UID) desc
LIMIT 1;
How do I do this in Mongo? EDIT: Example Library
{
"Date_Checked_Out":" 2014-01-01 09:34:36.206",
"Day":"Wednesday",
"Borrower_Category":" Undergraduate Student",
"Item_Barcode":"00000000012345'",
"Title":" Bob's Day at the Beach",
"Material_Format":" BOOK",
"Loan_Policy applied to item":" 0.10Day 2Week Loan",
"Due_Date":" 2013-12-19 00:45:00.0",
"Due_Day":"Thursday",
"Number_times_renewed":" 0",
"Institution":"FREED HARDEMAN UNIV; LODEN-DANIEL LIBR",
"Home_Branch": 15243,
"Shelving_Location":" Stacks; 1st Floor",
"Call_Number":" BV640 .B37 1989",
"UID":" 15243ea5-421f-4cec-b091-394586adfe2b"
}
Upvotes: 1
Views: 1871
Reputation: 19700
This is the equivalent aggregation pipeline command:
Use the $group
operator to group the records based on the UID
field.
Sort
and then limit
the first group.
db.collection.aggregate([{
$group: {
"_id": "$UID",
"count": {
$sum: 1
}
}
},
{
$sort: {
"count": -1
}
},
{
$limit: 1
}
])
Upvotes: 5