$push 修饰符:用于往数组中追加元素
db.workmates.update({name:'xiaowang'},{$push:{interseta:"PHP"}})
$ne 修饰符:如果 选择字段的值不等于给定的值或者该字段不存在
selects the documents where the value of thefield
is not equal to the specifiedvalue
. This includes documents that do not contain thefield
.
> db.c1.find() { "_id" : ObjectId("4fb4af85afa87dc1bed94330"), "age" : 7, "length_1" : 30 } { "_id" : ObjectId("4fb4af89afa87dc1bed94331"), "age" : 8, "length_1" : 30 } { "_id" : ObjectId("4fb4af8cafa87dc1bed94332"), "age" : 6, "length_1" : 30 } // 查询age 的值不等于7 的数据 > db.c1.find( { age : { $ne : 7 } } ); { "_id" : ObjectId("4fb4af89afa87dc1bed94331"), "age" : 8, "length_1" : 30 } { "_id" : ObjectId("4fb4af8cafa87dc1bed94332"), "age" : 6, "length_1" : 30 }
$addToSet 修饰符:向数组中添加一个值,如果该值存在,则不进行任何操作。
The
$addToSet
operator adds a value to an array unless the value is already present, in which case$addToSet
does nothing to that array.
> db.c1.find() { _id: 1, letters: ["a", "b"] } // 执行$addToSet db.c1.update({_id:1},{$addToSet:{ letters:"c" }})
$each 修饰符:向数组中批量添加值
可以结合$addToSet 和 $push 使用
db.students.update( { name: "joe" }, { $push: { scores: { $each: [ 90, 92, 85 ] } } } )
数组定位修改
修改数组索引为2的值为"code"
db.workmates.update({name:'xiaowang'},{$set:{"interset.2":"code"}})
runCommand
您可以使用 MongoDatabase.runCommand() 方法运行所有原始数据库操作,并返回执行结果
findAndModify
修改并返回单个文档,如果需要返回修改后的,需要指定new 为true
var myModify = { findAndModify: "workmates", query: { name: "xiaowang" }, update:{$set:{age:10}}, new:true, //返回修改后的值 fields:{name:true,age:true} // 需要返回的值 }; var result = db.runCommand(myModify);
查询操作
// 虚拟的文档数据: var db = connect("company"); function WorkMate(name, age, skill) { this.name = name; this.age = age; this.skill = skill; } var nameList = ["慎", "嘉文四世", "赵信", "德莱厄斯", "易", "贾克斯"]; var ageList = [20, 30, 40, 33, 22, 55]; var skillList = [ ["奥义!暮临", "奥义!魂佑", "奥义!影缚", "秘奥义!慈悲度魂落"], ["巨龙撞击", "黄金圣盾", "德玛西亚军旗", "天崩地裂"], ["三重爪击", "狂战怒吼", "无畏冲锋", "新月横扫"], ["大杀四方", "致残打击", "无情铁手", "诺克萨斯断头台"], ["阿尔法突袭", "冥想", "无极剑道", "高原血统"], ["跳斩", "蓄力一击", "反击风暴", "宗师之威"], ]; var start = 6; var heros = [] while (start-- > 0) { heros.push( new WorkMate(nameList[start],ageList[start],skillList[start]) ) } db.heros.insert(heros); print('INSERT SUCCESS');
// 查询操作 var db = connect("company"); // 精确查询 db.heros.find({ name:'贾克斯' }); // 查询年龄大于30 小于等于50的 db.heros.find({ age:{$gt:30,$lte:50} }) // 查询年龄不等于33的 db.heros.find({ age:{$ne:33}, }) // 查询名称不等于赵信的 db.heros.find({ name:{$ne:"赵信"}, },{ name:1 }) // 从查询结果取出自己需要的字段 db.heros.find({ name:'贾克斯' },{ name:1, age:1, _id:0 });