一、數(shù)組相關(guān)
1、 更新數(shù)組中的某個(gè)值
users 表中有一條記錄:
{
name:'Tom'
friends : [
{ name: '張三', age: 1 },
{ name: '李四', age: 2 }
]
}
現(xiàn)在我們要改李四的年齡為 3歲:
> db.users.update({
name:'Tom',
'friends.name':'李四'
},{
$set:{
'friends.$.age' : 3
}
});
注意
$
定位符,該方法只會(huì)修改第一條匹配到的數(shù)據(jù)
2、刪除數(shù)組中的一條記錄
文檔格式如下:
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502"),
"links": [
{
"name": "Google",
"url": "http://www.google.com"
},
{
"name": "Baidu",
"url": "http://www.baidu.com"
},
{
"name": "SoSo",
"url": "http://www.SoSo.com"
}
]
}
1)、根據(jù)屬性刪:要?jiǎng)h除 links 中 name 是 Baidu 的記錄
db.collection.update(
{ _id: ObjectId('id') },
{ $pull: { links: { name: 'Baidu' } } }
);
2)、根據(jù)索引刪除,索引從 0 開始
db.collection.update(
{ _id: ObjectId('id') },
{ $unset: { 'links.1': 1 } }
);
這種方式會(huì)導(dǎo)致:原來的值會(huì)替換為 null
3、排序
1)、元素為對(duì)象類型
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502"),
"links": [
{
"name": "Google",
"age": 12
},
{
"name": "Baidu",
"age": 19
},
{
"name": "SoSo",
"age": 9
}
]
}
語法:按照links
中每個(gè)對(duì)象的age
字段 進(jìn)行倒序
排列
db.collection.update(
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502")
},
{
$push: {
links: {
$each: [], // 如果只為排序,這個(gè)需要給一個(gè)空數(shù)組
$sort: { age: -1 } # $sort 必須與 $push 和 $each配合使用
}
}
}
)
2)、基礎(chǔ)類型
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502"),
"links": [5, 8, 1, 23, 9]
}
語法:對(duì)links
字段倒序排列
db.collection.update(
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502")
},
{
$push: {
links: {
$each: [], // 如果只為排序,這個(gè)需要給一個(gè)空數(shù)組
$sort: -1 # $sort 必須與 $push 和 $each配合使用
}
}
}
)
4、新增元素
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502"),
"links": [5, 8, 1, 23, 9]
}
語法:避免重復(fù) $addToSet
db.collection.update(
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502")
},
{
$addToSet: {
links: {
$each: [8, 12, 15] # 8 重復(fù)了,不會(huì)被添加。
}
}
}
)
三、經(jīng)緯度篩選
1、弧度查詢,則以 ** 公里數(shù) ** 除以6371,如“附近500米的餐廳”:
> db.runCommand( { geoNear: "places", near: [ 121.4905, 31.2646 ], spherical: true,
$maxDistance: 0.5/6371 })
4、根據(jù)數(shù)組中是否含有某個(gè)元素來查詢匹配的記錄
$all
> db.fruitshop.find();
{ "_id" : ObjectId("5022518d09248743250688e0"), "name" : "big fruit", "fruits" : [ "apple", "pear", "orange" ] }
{ "_id" : ObjectId("502251a309248743250688e1"), "name" : "good fruit", "fruits" : [ "banana", "pear", "orange" ] }
{ "_id" : ObjectId("502251c109248743250688e2"), "name" : "good fruit", "fruits" : [ "banana", "apple", "tomato" ] }
> db.fruitshop.find({"fruits":{"$all":["apple","banana"]}});
{ "_id" : ObjectId("502251c109248743250688e2"), "name" : "good fruit", "fruits" : [ "banana", "apple", "tomato" ] }
>
5、導(dǎo)出為CSV
mongoexport -d myDB -c user -f _id,name,password,adress --csv -o ./user.csv
-d 標(biāo)示 數(shù)據(jù)庫
-c 標(biāo)示 數(shù)據(jù)表
-f 需要提取的field用逗號(hào)分隔
-o 輸出路徑
6、分組查詢
aggregate-分組查詢
group這個(gè)對(duì)象。
后面的字段是用來分組的字段,如果不取值,可以寫成: _id:null
amount',用于計(jì)算該字段的加和。
如果想統(tǒng)計(jì)個(gè)數(shù),可以這么寫:total:{$sum : 1};