国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > MongoDB > 正文

MongoDB操作符中的$elemMatch問題

2020-10-29 18:40:37
字體:
供稿:網(wǎng)友

問題

如果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})

此時會得到結(jié)果嗎?

最開始我想當然的以為是不會出現(xiàn)結(jié)果的,但結(jié)果往往與期望背道而馳。

什么,一瞬間我陷入了迷茫,Mongo的查詢結(jié)果不是必須都滿足所有條件的嗎?

分析

不信邪的我又嘗試了喜聞樂見的小白查詢

db.getCollection('Persion').find({"name": "趙小明", "age": 18})

這次結(jié)果為空,嗯,這才是我熟悉的Mongo嘛?

那這兩次查詢有啥區(qū)別呢?不同有兩點

  • 是否為二級字段
  • 是否為數(shù)組

那我們將數(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})

此次結(jié)果為空集

接下來嘗試查詢

db.getCollection('Persion').find({"relatives.name": "趙剛", "relatives.relationship": 0})

此次可得到一條結(jié)果

通過上述兩次查詢基本可以排除二級字段的影響

那就是數(shù)組的原因了,那具體是為什么呢?

將數(shù)據(jù)還原為最初的格式,繼續(xù)進行不同的查詢

db.getCollection('Persion').find({"relatives.name": "趙剛", "relatives.relationship": 2})

此次結(jié)果為空集

那我們可以得到結(jié)論,對于數(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}}})

此時可以得到結(jié)果,但

db.getCollection('Persion').find({"relatives":{"$elemMatch":{"name": "趙四", "relationship": 1}}})

結(jié)果為空集

結(jié)語

此操作符和索引也有一些不得不說的事,今天就不在這里細說了,之后我會專門總結(jié)一篇有關(guān)MongoDB索引相關(guān)的博客

等不及的看官可以自行百度Google一下。

總結(jié)

到此這篇關(guān)于MongoDB操作符之$elemMatch的文章就介紹到這了,更多相關(guān)MongoDB操作符之$elemMatch內(nèi)容請搜索武林網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持武林網(wǎng)!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 博爱县| 洱源县| 鄂州市| 花垣县| 腾冲县| 客服| 云安县| 长宁县| 丰都县| 龙胜| 黔西| 本溪市| 五常市| 綦江县| 芦溪县| 云霄县| 文安县| 门源| 香港 | 镇沅| 中宁县| 苍山县| 湖北省| 措美县| 闵行区| 平谷区| 辉县市| 黄骅市| 合肥市| 稷山县| 黄石市| 内乡县| 西安市| 平谷区| 顺义区| 仪陇县| 大名县| 怀安县| 当涂县| 兰考县| 黄石市|