1. /* Schema中定义模糊数组,可以添加,不能删除 */
  2. const UserSchema = new Schema({
  3. name:String,
  4. collects:[
  5. {
  6. labels:Array,
  7. _id:Schema.Types.ObjectId,
  8. pic:String,
  9. title:String,
  10. slogo:String,
  11. evaluate:String,
  12. rating:String,
  13. collected:Boolean
  14. }
  15. ]
  16. })

1-1 $pull删除数组中符合条件的值

  1. //stores
  2. {id:1000,
  3. cartList:[
  4. {productId:1001,name:'手机'},
  5. {productId:1002,name:"电脑"},
  6. {productId:1003,name:"平板"}
  7. ]
  8. }
  1. db.stores.update({id:1000},{$pull:{cartList:{productId:1001}}})

1-2 $push向数组中添加一条数据

  1. db.stores.update({id:1000},{$push:{cartList:{productId:1004,name:"电动车"}}})

1-3 根据某个字段对内嵌数组查询

  1. db.stores.find({'cartList.productId':1001})
  2. UserModel.find({"history._id":id})
  3. User.find({userId,"cartList._id":id})

1-4 只想查询内嵌的数组

  1. db.user.find({},{history:1})

1-5 修改内嵌数组中的某个字段

  1. // 如果记录匹配到多条,用$只进行了第一个元素的更改,需要多条修改那么用$[],如果指定下标修改,那么把$修改为元素的下标即可,索引从0开始
  2. db.user.update({username:'zheng','cartList._id':id},{$set:{'cartList.$.salePrice':3550}})