Q: 查詢字段是否存在
db.collections.find({filed: {$exists: true}})
Q: 查詢不存在字段field的數(shù)據(jù)并且設置字段為newValue
db.collections.updateMany({filed: {$exists: false}}, {$set: {filed: newValue}}
Q: 數(shù)據(jù)中存在知識點屬性,該屬性結(jié)構為
points: [
{
point: { // 最后一個知識點
type: ObjectId,
ref: 'point'
},
path: [String] // 知識點路徑
}
],
需要查詢知識點a及知識點a之下所有知識點的數(shù)據(jù)
db.collections.find({
points: {
$elemMatch: {
path: {
$all: point // point為知識點a的path
}
}
}
})
Q: 二維數(shù)組元素查詢,結(jié)構為
{
"a": [["yellow", "num"], ["blue", "num"]]
}
查出有’yellow’的數(shù)據(jù)
db.collections.find({'a':{'$elemMatch':{'$elemMatch':{'$in':['yellow']}}})
Q: 刪除數(shù)據(jù)的屬性filed
db.collections.updateMany({}, {$unset: {filed: 1}}
Q: 查詢數(shù)據(jù)中數(shù)組大于n的數(shù)據(jù)
數(shù)組元素個數(shù)可以使用$size,如查詢數(shù)組個數(shù)為n的數(shù)據(jù):
db.collections.find({list: {$size: n}})
但是$size不能使用范圍運算??梢允褂?where關鍵字
db.collections.find({$where: "this.list.length > n"})
這種方法速度較慢,可以使用
db.collections.find({"list.n": {$exists: true}})
這種方法速度更快,但是前提是數(shù)組中的元素不能為空值。另外也有人添加size屬性,專門用來保存數(shù)組長度,此時,查詢size的大小即可。
Q: 刪除數(shù)據(jù)中filed字段重復的數(shù)據(jù)
- 新建立一個new集合,用于保存去重后的數(shù)據(jù)。且再new集合中建立唯一索引
db.new.ensureIndex({"field":1},{"unique":true})
- 將old集合中的數(shù)據(jù)使用mongoexport導出,然后mongoimport導入到new集合中
mongoexport -d test -c old -o data.dat
mongoimport -d test -c new data.dat
Q: mongodb不聯(lián)網(wǎng)無法連接
數(shù)據(jù)庫地址使用127.0.0.1,而不使用localhost
參考:
數(shù)組相關查詢
MongoDB查詢(數(shù)組、內(nèi)嵌文檔和$where)
數(shù)據(jù)更新命令
查詢命令