mongodb query
query document 结构
db.collection.find( <query filter>, <projection> )
a query filter: specify which documents to return.
a query projection : specifies which fields from the matching documents to return. The projection limits the amount of data that MongoDB returns to the client over the network.
You can optionally add a cursor modifier to impose limits, skips, and sort orders. The order of documents returned by a query is not defined unless you specify a sort().
Query on Embedded Documents
Exact Match
To specify an exact equality match on the whole embedded document, use the query document {
: } where is the document to match. Equality matches on an embedded document require an exact match of the specified , including the field order.
Equality Match on Fields
db.users.find( { "favorites.artist": "Picasso" } )
Query on Arrays
When the field holds an array, you can query for an exact array match or for specific values in the array
If you specify multiple conditions without using the $elemMatch operator, then some combination of the array elements, not necessarily a single element, must satisfy all the conditions; i.e. different elements in the array can satisfy different parts of the conditions
exact match
Equality matches on the array require that the array field match exactly the specified
db.users.find( { badges: [ "blue", "black" ] } )
Match an Array Element
Equality matches can specify a single element in the array to match. These specifications match if the array contains at least one element with the specified value
db.users.find( { badges: "black" } )
Match a Specific Element of an Array
badges is an array that contains "black" as the first element:
db.users.find( { "badges.0": "black" } )
Specify Multiple Criteria(标准) for Array Elements
Single Element Satisfies the Criteria
$elemMatch : at least one array element
db.users.find( { finished: { $elemMatch: { $gt: 15, $lt: 20 } } } )
Combination of Elements Satisfies the Criteria
e.g., one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both
db.users.find( { finished: { $gt: 15, $lt: 20 } } )
使用操作符
Comparison
小于等于$lte
大于 $gt
大于或等于$gte
不等于$ne
$in 在数组里
$nin 不在数组里
logical
$or
$and 逗号也表示$and
$not
$nor returns all documents that fail to match both clauses
Element
$exists 存在这个field
$type 类型匹配
Evaluation(计算)
$mod 模运算
$regex regular expression.
$text Performs text search.
$where satisfy a JavaScript expression.
Array
$all contain all elements specified in the query.
$elemMatch
$size 元素个数
comments
$comment Adds a comment to a query predicate.
associates a comment to any expression taking a query predicate.
for example:
db.collection.find( { <query>, $comment: <comment> } )
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步