集合查询 db.TableName.find({"listData.listData1.field":2}); 非集合查询 db.TableName.find({"field":2}); 多条件查询 db.TableName.find({"field1":1,"field2":"test"}); 非集合新增 db.TableName.update({},{$set: {"new_field":1}}, {multi:true}) db.TableName.update({"new_field":{$exists:false}},{$set:{"new_field":NumberInt("0")}},{multi:true}) 集合新增 db.Vac_Order.find({}).forEach(function(order){ order.OrderDetail.forEach(function(detail){ detail.MappingDetail.forEach(function(mapping){ if(!mapping.newField){ mapping.newField=0 //新增字段 } }) }) db.Vac_Order.save(order) }) 非集合删除 db.TableName.update({}, {$unset: {"new_field":1}},{multi:true}) db.TableName.deleteMany({"field":"条件"})= db.TableName.deleteOne({"field":"条件"}) 集合删除 db.Vac_Order.find({}).forEach(function(order){ order.OrderDetail.forEach(function(detail){ detail.MappingDetail.forEach(function(mapping){ if(mapping.newField){ delete mapping.newField//删除字段 } }) }) db.Vac_Order.save(order) }) 非集合修改 db.TableName.update({"field":"条件"},{$set:{"field":"新值"}},{multi:true}) 集合修改
集合修改1
db.Vac_Order.find({}).forEach(
function(order)
{
order.OrderDetail.forEach(
function(detail)
{
detail.MappingDetail.forEach(
function(mapping)
{
if(mapping.newField)
{ mapping.newField=1//重新赋值 }
})
})
db.Vac_Order.save(order)
})
集合修改2
var i=0;
db.Vac_Regional_AreaInventory.find({"RegionCode" : "630000","SpecificationQty" : 0,}).forEach(
function(item)
{
if(item.AccountQty!=parseFloat(item.AvailableQty)+parseFloat(item.AllocatedQty)+parseFloat(item.UnusedQty))
{
print(item) ;// print(item.AccountQty+'/'+(parseFloat(item.AvailableQty)+parseFloat(item.AllocatedQty)+parseFloat(item.UnusedQty)))
print(i);
i++
db.Vac_Regional_AreaInventory.update({'_id':item._id},{$set:{'AllocatedQty':item.AccountQty}},{multi:true})
}
)
查询操作符 操作符"$gt" 、"$gte"、 "$lt"、 "$lte"(分别对应">"、 ">=" 、"<" 、"<=") 示例如下 1:查询为10-100(包含10但不含100)的数据 db.TableName.find( { field: { $gte: 10 ,$lt:100} } 2:查询不等于99的数据 db.TableName.find( { field: {$ne:99} } 键值为null查询操作 如何检索出field键值为null的文档,我们使用in"、"">"in"、"where"操作符,"$in"判断键值是否为null,"$exists"判定集合中文档是否包含该键 示例如下: 1:找条件为X且Y的field列为null的数据 db.TableName.find({field:{$in:[null],$exists:true },"where_field" : X, "where_field" : Y}) "$in" 2:查询出field键值为value1或者value2的文档 db.TableName.find( { field: { $in: [ value1, value2] } } ) "$nin" db.TableName.find( { field: { $nin: [ value1, value2] } } )
MongoDB聚合函数查询
eg: 实现Select Group by Having
SQL:SELECT BatchNo, ManufacturerId,Specification,VaccineId,COUNT(BatchNo) sum
FROM student
GROUP BY id
HAVING sum>1;
MongoDB实现
db.Vac_ManufacturerMaping.aggregate(
{"$group": {_id:{BatchNo:"$BatchNo",ManufacturerId:"$ManufacturerId",Specification: "$Specification",VaccineId:"$VaccineId"}, "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }
)