問題
如果MongoDB 數(shù)據(jù)庫集合中僅存在一條記錄
{
"_id" : ObjectId("5e6b4ef546b5f44e5c5b276d"),
"name" : "趙小明",
"used_name" : [
"趙明",
"趙小朋"
],
"age" : 16,
"gender" : 0,
"relatives" : [
{
"name" : "趙剛",
"relationship" : 0
},
{
"name" : "秀英",
"relationship" : 1
}
]
}
我們執(zhí)行查詢
db.getCollection('Persion').find({"relatives.name": "趙剛", "relatives.relationship": 1})
此時會得到結果嗎?
最開始我想當然的以為是不會出現(xiàn)結果的,但結果往往與期望背道而馳。
什么,一瞬間我陷入了迷茫,Mongo的查詢結果不是必須都滿足所有條件的嗎?
分析
不信邪的我又嘗試了喜聞樂見的小白查詢
db.getCollection('Persion').find({"name": "趙小明", "age": 18})
這次結果為空,嗯,這才是我熟悉的Mongo嘛?
那這兩次查詢有啥區(qū)別呢?不同有兩點
那我們將數(shù)據(jù)改為
{
"_id" : ObjectId("5e6b4ef546b5f44e5c5b276d"),
"name" : "趙小明",
"used_name" : [
"趙明",
"趙小朋"
],
"age" : 16,
"gender" : 0,
"relative" : {
"name" : "趙剛",
"relationship" : 0
}
}
繼續(xù)執(zhí)行查詢
db.getCollection('Persion').find({"relatives.name": "趙剛", "relatives.relationship": 1})
此次結果為空集
接下來嘗試查詢
db.getCollection('Persion').find({"relatives.name": "趙剛", "relatives.relationship": 0})
此次可得到一條結果
通過上述兩次查詢基本可以排除二級字段的影響
那就是數(shù)組的原因了,那具體是為什么呢?
將數(shù)據(jù)還原為最初的格式,繼續(xù)進行不同的查詢
db.getCollection('Persion').find({"relatives.name": "趙剛", "relatives.relationship": 2})
此次結果為空集
那我們可以得到結論,對于數(shù)組字段,每個查詢條件僅需有數(shù)組中的一項滿足條件即可,而不是數(shù)組中必須存在一項滿足所有查詢條件。
那如果我想達到后面的效果要怎么做呢?
解決
此時,我們需要用到我們今天的主角 $elemMatch
,它的官方定義是這樣的:
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
{ field>: { $elemMatch: { query1>, query2>, ... } } }
If you specify only a single condition in the $elemMatch expression, you do not need to use $elemMatch.
You cannot specify a $where expression in an $elemMatch.
You cannot specify a $text query expression in an $elemMatch.
那上邊的查詢我們可以改成
db.getCollection('Persion').find({"relatives":{"$elemMatch":{"name": "趙四", "relationship": 0}}})
此時可以得到結果,但
db.getCollection('Persion').find({"relatives":{"$elemMatch":{"name": "趙四", "relationship": 1}}})
結果為空集
結語
此操作符和索引也有一些不得不說的事,今天就不在這里細說了,之后我會專門總結一篇有關MongoDB索引相關的博客
等不及的看官可以自行百度Google一下。
總結
到此這篇關于MongoDB操作符之$elemMatch的文章就介紹到這了,更多相關MongoDB操作符之$elemMatch內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- MongoDB 管道的介紹及操作符實例
- 基于MongoDB數(shù)據(jù)庫的數(shù)據(jù)類型和$type操作符詳解