MongoDB
常用命令
db.createCollection('mytestcopy');
db.Test.updateMany({}, {'$rename': {'raw_field': 'new_field'}}, false, true)
db.getCollection('集合名').update({}, {$rename : {"修改前字段名" : "修改后字段名"}}, {multi:true})
db.table.update({}, {$set: {content:""}}, {multi: true})
db.XXX.update({
"字段名": {
"$exists": true
}
}, {
"$unset": {
"字段名":null
}
}, {
multi: true
});
var tags = ["nosql","mongodb","document","developer","popular"];
var types = ["technology","sociality","travel","novel","literature"];
var books=[]; for(var i=0;i<50;i++){ var typeIdx = Math.floor(Math.random()*types.length);
var tagIdx = Math.floor(Math.random()*tags.length);
var favCount = Math.floor(Math.random()*100);
var book = { title: "book-"+i, type: types[typeIdx], tag: tags[tagIdx], favCount: favCount, author: "xxx"+i };
books.push(book) }db.mytest.insertMany(books);
db.mytest.find({});
db.books.find({_id:ObjectId("61caa09ee0782536660494d9")});
db.XXX.deleteMany({});
db.XXX.drop();
db.XXX.remove({_id:ObjectId("6242df12f9506c38a8180448")})
db.getCollection("XXX").insert( {
_id: ObjectId("6242df12f9506c38a8180448"),
name: "项目"
});
db.XXX.find().forEach(function(x){db.XXX.insert(x)});
db.XXX.find().forEach(function(x) {
db.XXX.update({
_id: x._id
}, {
$set: {
字段名: x.字段名
}}, false, true
)
});
db.tblCard.find({"lCycle":2}).forEach(
function(item){
db.tblCard.update({"_id":item._id},{"$set":{"tPAFlow":item.pFlow}},false,true)
}
);
db.XXX.updateMany({'对象名.属性名': 'a'}, {$set: {'对象名.$.属性名': 'b'}}, false, true);
db.getCollection("XXX").update({_id:ObjectId("123")},{$set:{"XXX": ["123"]}})
db.XXX.find({ $and : [{"字段A" : null}, ] }).count();
db.XXX.updateMany({ $and : [{"字段A" : null}] }, {$set: {'字段A': 'A'}}, false, true);
db.XXX.updateMany({}, {'$rename': {'raw_field': 'new_field'}}, false, true)
use db_source;
var test_copy = db_source.table.find();
use db_target;
test_copy.forEach(function(d){db.coll_target.insert(d)});
db.XXX.aggregate([
{$group:{_id:{字段名A:"$字段名A",字段名B:"$字段名B"},count: { $sum: 1 }}},
{ $match: { count: { $gt: 1 } } }
])
db.test.aggregate({"$group":{"_id":"$userid"}} )
db.test.aggregate({"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}})
db.test.aggregate(
{"$match":{"userid":{"$in":["1","2"]}}},
{"$group":{"_id":"$userid"}}
)
或者
db.test.aggregate(
{"$match":{"userid":{"$in":["1","2"]}}},
{"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}}
)
或者having聚合查询
db.test.aggregate(
{"$match":{"userid":{"$gt":"10"}}},
{"$group":{"_id":"$userid",'avg':{"$avg":"$price"}}},
{"$match":{"avg":{"$gt":35}}}
)
db.XXX.aggregate(
{"$group":{"_id":{"字段A":"$字段A","字段B":"$字段B"},字段A:{"$first":"$字段A"},字段B:{"$first":"$字段B"},count: { $sum: 1 }}},
{ "$match": { count: { $gt: 1 } } },
{"$project" : {_id:0}}
).forEach(function(item) {
db.XXX.updateMany({ $and : [ {"字段A" : item.字段A},{"字段B" : item.字段B}]}, {$set: {'enabled': true}}, false, true);
});
db.XXXX.aggregate([
{
$match: {
_id: ObjectId("123")
}
},
{
$project:{
"id":{
"$convert":{
"input":"$_id",
"to":"string"
}
}
}
},
{
$lookup: {
from: "XXXX",
localField: "id",
foreignField: "parentId",
as: "childer"
}
}
])
db.XXXX.updateMany({"数组字段名":{"$in":[null]}}, {'$pull': {'数组字段名': null}}, false, true);
db.XXX.find({
"$and": [{
"字段名": "A"
}]
}).forEach(function(item) {
db.XXX.updateMany({
"$and": [{
"字段名": "ADMIN"
}, {
"字段名":{$in:item.ids}
}]
}, {
$addToSet: { "ids": { $each: item.ids } }
}, false, true);
});
var result= "https://www.baidu.com";
db.article.find().forEach(
function(item) {
var detail = item.articleDetail;
if (detail != null) {
print("detail start change:" + item._id);
detail = detail.toString().replace(/http[s]*:\/\/[^\/]*/gi, result);
db.article.update({"_id":item._id}, {$set:{"articleDetail": detail}});
}
if (item.images != null) {
item.images.forEach(
function(arr, index) {
var url = item.images[index].url.toString();
print('old:' + url);
url = url.replace(/http[s]*:\/\/[^\/]*/gi, result);
print("new:" + url);
var tmp = "images."+index+".url";
tmp = JSON.parse('{"$set":{"'+ tmp + '" : "'+url+'"}}');
db.article.update({"_id":item._id}, tmp);
}
);
}
}
);
db.XXXX.find({"phone":/^\+|-/});
db.XXXX.find({
"deletedFlag": false,
"phone":/^\+|-/
}).forEach(
function(item) {
var phone = item.phone.toString().replace(/^\+*[-]*|-*/, "");
print(phone);
item.phone = phone;
db.XXXX.save(item);
}
)
db.XXX.aggregate([
{
"$match": {
"type": "A",
"deletedFlag": false
}
},
{
$group: {
"_id": {
"字段名": "$字段名",
"字段名": "$字段名"
},
count: {
$sum: 1
},
dups:{$addToSet:'$_id'}
}
},
{
$match: {
count: {
$gt: 1
}
}
}
]).forEach(function(it){
it.dups.shift();
db.XXX.remove({_id: {$in: it.dups}});
});
db.XXX.updateMany( {_id:ObjectId("123")}, {"$set": {"enabled":true}}, false, true)
db.getCollection("XXX").aggregate([{
"$match": {
"$and": [{
"$and": [{
"enabled": false
}]
}]
}
}, {
"$unwind": {
"path": "$字段名",
"preserveNullAndEmptyArrays": true
}
}, {
"$group": {
"_id": {
"字段名": "$字段名",
"字段名": "$字段名"
},
"字段名": {
"$sum": "$字段名"
}
}
}, {
"$group": {
"_id": "$_id.字段名",
"别名": {
"$push": {
"别名": "$_id.字段名",
"别名": "$字段名"
}
}
}
}, {
"$sort": {
"_id": 1
}
}]);
db.XXX.aggregate([
{ $group: { _id: { 字段名: "$字段名" }, uniqueIds: { $addToSet: "$_id" }, count: { $sum: 1 } } },
{ $match: { count: { $gt: 1 } } },
{
$project: {
_id: { $arrayElemAt: ["$uniqueIds", 0] },
remainingIds: { $slice: ["$uniqueIds", 1, { $size: "$uniqueIds" }] }
}
}
]).forEach(function(doc) {
db.XXX.deleteMany({ _id: { $in: doc.remainingIds } });
});