1 số câu lệnh hay dùng
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
// Connect db mongo localhost:3001 mongo mongodb://root:example@localhost:27017/?authSource=admin // show database show dbs // connect database: mydata use mydata // Show all collections show collections // Basic find db.books.find() // Find document in collection: rocketchat_settings db.getCollection('rocketchat_settings').findOne({_id: "User's Vacation Status"}) // Destroy db.getCollection('rocketchat_settings').remove({_id: "User's Vacation Status"}) // Remove field tabId db.getCollection("rocketchat_custom_emoji").update( { tabId: { $exists: true } }, { $unset: { tabId: 1 } }, { multi: true }, ); // Find _id but no know Collection db.getCollectionNames().forEach(function(collName) { var doc = db.getCollection(collName).findOne({"_id" : "FfEG6ycEqCP8Lxbmm"}); if(doc != null) print(doc._id + " was found in " + collName); }); // Change one field string -> int, use aggregate [] db.getCollection('rocketchat_settings').updateOne({_id:"LDAP_Port"},[ { $set: { value: { $toInt: "$value" }, status: '$otherField' } } ]) db.getCollection('rocketchat_custom_emoji').aggregate([ { $sort: { _updatedAt: -1 } }, { $group: { _id: '$tabId', emojis: { $push: '$$ROOT' } } }, { $lookup: { from: 'rocketchat_custom_emoji_tab', localField: '_id', foreignField: '_id', as: 'tab', }, }, { $project: { _id: false, emojis: 1, tab: 1, tabName: { $cond: [{ $gt: [{ $size: '$tab' }, 0] }, { $arrayElemAt: ['$tab.tabName', 0] }, 'Smilemates'], }, }, }, { $sort: { tabName: 1 } }, ]).pretty() |
2. Sử dụng Aggregate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
this.model.rawCollection().aggregate([ { $sort: { _updatedAt: -1 } }, { $group: { _id: '$tabId', emojis: { $push: '$$ROOT' } }, }, { $lookup: { from: EmojiCustomTab.collectionName, localField: '_id', foreignField: '_id', as: 'tab', }, }, { $project: { _id: false, emojis: 1, tab: 1, tabName: { $cond: [{ $gt: [{ $size: '$tab' }, 0] }, { $arrayElemAt: ['$tab.tabName', 0] }, ''], }, tabId: { $cond: [{ $gt: [{ $size: '$tab' }, 0] }, { $arrayElemAt: ['$tab._id', 0] }, ''], }, }, }, ]).toArray(); this.model.rawCollection().aggregate([ { $match: { _id } }, { $lookup: { from: EmojiCustomTab.collectionName, localField: 'tabId', foreignField: '_id', as: 'tab', }, }, { $addFields: { tabName: { $cond: [{ $gt: [{ $size: '$tab' }, 0] }, { $arrayElemAt: ['$tab.tabName', 0] }, 'Smilemates'], }, tabId: { $cond: [{ $gt: [{ $size: '$tab' }, 0] }, { $arrayElemAt: ['$tab._id', 0] }, ''], }, }, }, ]).toArray(); |