Here some useful commands
Add rows into a collection
# command line
mongoimport -u "root" -p "<password>" --authenticationDatabase "admin" [--jsonArray] --db <schema> --collection <collection> --file <filename>
Export a collection
# command line
mongoexport -u "root" --authenticationDatabase "admin" -d <schema> -c <collection> -o <filename>
Find/Count occurrences that match a size
/* robo3t syntax */
db.getCollection('collection-name').find({ 'field-name': { $size: 2 } });
db.getCollection('sa-access-points').count({ 'field-name': { $size: 2 } };
Update many
/* robo3t syntax - update all values of the field "b" to value "c" in the collection "a" */
db.getCollection('a').updateMany({ }, {
$set: {
"b": 'c'
}
});
/* if you would like to update all the element called propertyToUpdate of a subarray */
db.getCollection("a").updateMany({
// other filters
"subarray": {$type: "array"} //make sure that the element is an array
}, {
$set: {
"subarray.$[].propertyToUpdate": "value"
},
});
/* mongoose syntax - complex update */
await this.database.connection.db.collection("collection-name").updateMany({
"obj1.prop1": { //obj1: [{prop1: "val", prop2: "abc"}, {prop1: "val", prop2: "dsa"}]
$in: "val"
}, //and
"obj1.prop2": 'abc' //exact match
}, {
$set: {
"obj1.$.prop2": 'bcd' //result obj1: [{prop1: "val", prop2: "bcd"}, {prop1: "val", prop2: "dsa"}]
}
});
Get, manipulate and replace
/* mongoose syntax - get all elements of a collection and replace it */
/* use it only for small amount of elems */
let elems = await this.database.connection.db.collection("collection").find({}).toArray();
for (let ele of elems) {
/* manipulate the object... */
await this.database.connection.db.collection('collection').replaceOne({ _id: ele._id }, ele);
}
0 Comments