find詳解

圖片.png

圖片.png

圖片.png


等價查詢某個數組:

db.getCollection("test").find(
    {
        tags: ["good","book","it","program"] 
    }
);

(//連順序都要是存進去的順序,不能變)


查詢數組裏的某一個值:

db.getCollection("test").find(
    {
        tags: "good"
    }
);


查詢有四個元素的數組:

db.getCollection("test").find(
    {
        tags: {$size: 4}
    }
);


查詢有或沒有指定字段的,指定字段爲null的情況:

db.getCollection("test").insert(
    [
        {_id: 2222, toy: null},
        {_id: 1112}
    ]
);
db.getCollection("test").find(
    {_id: 2222, toy: null}
);
db.getCollection("test").find(
    toy: null
); //報錯
db.getCollection("test").find(
    {_id: 2222, toy: {$exists: true}}
); //找出來了當前這條
db.getCollection("test").find(
    {toy: {$exists: true}}
); //找出來了當前這條
db.getCollection("test").find(
    {toy: {$exists: false}}
); //找出所有沒有toy這個字段的


查找返回值遊標:

db.getCollection("test").find().forEach(function(item) {
    print(item.name, item.price, item.tags);
});


limit,skip方法:

db.getCollection("test").find().limit(1)
db.getCollection("test").find().skip(2)


$in的查詢:

db.getCollection("test").find(
    {
        _id: {
            $in: {12, objectId("56970120abt538296thg0y6")}
        }
    }
); //查找_id等於12或objectId("56970120abt538296thg0y6")的文檔記錄

($in 用於不同文檔指定同一個Key 進行或條件匹配, $or 可以指定多個Key 或條件匹配。)


區間查找:

db.getCollection("test").find(
    {
        price: {$gt: 3, $lt: 33}
    }
); //查詢價格範圍大於3小子33的值。可用於文檔數值字段,也可以用於數組字段
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章