MongoDB操作符之$elemMatch


問題

如果MongoDB 數據庫集合中僅存在一條記錄

{
    "_id" : ObjectId("5e6b4ef546b5f44e5c5b276d"),
    "name" : "趙小明",
    "used_name" : [ 
        "趙明", 
        "趙小朋"
    ],
    "age" : 16,
    "gender" : 0,
    "relatives" : [ 
        {
            "name" : "趙剛",
            "relationship" : 0
        }, 
        {
            "name" : "秀英",
            "relationship" : 1
        }
    ]
}

我們執行查詢

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

此時會得到結果嗎?

最開始我想當然的以為是不會出現結果的,但結果往往與期望背道而馳。
什么,一瞬間我陷入了迷茫,Mongo的查詢結果不是必須都滿足所有條件的嗎?

分析

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

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

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

那這兩次查詢有啥區別呢?不同有兩點

  • 是否為二級字段
  • 是否為數組

那我們將數據改為

{
    "_id" : ObjectId("5e6b4ef546b5f44e5c5b276d"),
    "name" : "趙小明",
    "used_name" : [ 
        "趙明", 
        "趙小朋"
    ],
    "age" : 16,
    "gender" : 0,
    "relative" : {
        "name" : "趙剛",
        "relationship" : 0
    }
}

繼續執行查詢

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

此次結果為空集

接下來嘗試查詢

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

此次可得到一條結果

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

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

將數據還原為最初的格式,繼續進行不同的查詢

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

此次結果為空集

那我們可以得到結論,對於數組字段,每個查詢條件僅需有數組中的一項滿足條件即可,而不是數組中必須存在一項滿足所有查詢條件。

那如果我想達到后面的效果要怎么做呢?

解決

此時,我們需要用到我們今天的主角$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一下。

最后,點個推薦唄,謝謝!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM