MongoDB操作符中的$elemMatch問題
問題
如果MongoDB 數(shù)據庫集合中僅存在一條記錄
{
"_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ù)組
那我們將數(shù)據改為
{
"_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ù)據還原為最初的格式,繼續(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內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MongoDB如何正確中斷正在創(chuàng)建的索引詳解
這篇文章主要給大家介紹了關于MongoDB如何正確中斷正在創(chuàng)建的索引的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
MongoDB快速入門筆記(七)MongoDB的用戶管理操作
這篇文章主要介紹了MongoDB快速入門筆記(七)MongoDB的用戶管理操作 的相關資料,需要的朋友可以參考下2016-06-06
Mongodb中MapReduce實現(xiàn)數(shù)據聚合方法詳解
Mongodb是針對大數(shù)據量環(huán)境下誕生的用于保存大數(shù)據量的非關系型數(shù)據庫,針對大量的數(shù)據。接下來通過本文給大家介紹Mongodb中MapReduce實現(xiàn)數(shù)據聚合方法詳解,感興趣的朋友一起學習吧2016-05-05

