在MongoDB中,查询语法主要使用BSON(类似于JSON)格式进行操作
db.collection_name.find_one({key: value})
示例:
db.users.find_one({username: "john_doe"})
db.collection_name.find({key: value})
示例:
db.users.find({age: {$gt: 18}})
db.collection_name.find({key: {$regex: "pattern", $options: "option"}})
示例:
db.users.find({username: {$regex: "j", $options: "i"}})
db.collection_name.find({}, {key1: 1, key2: 1, _id: 0})
示例:
db.users.find({}, {username: 1, email: 1, _id: 0})
db.collection_name.find().skip(n).limit(m)
示例:
db.users.find().skip(10).limit(5)
db.collection_name.find().sort({key: order})
示例:
db.users.find().sort({age: -1})
db.collection_name.find().limit(n)
示例:
db.users.find().limit(10)
db.collection_name.find().skip(n)
示例:
db.users.find().skip(10)
db.collection_name.aggregate([pipeline])
示例:
db.users.aggregate([
{ $group: { _id: "$city", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
这些仅仅是MongoDB查询语法的基本操作,实际应用中可以根据需求进行更复杂的查询和操作。