Zac Fukuda
063

MongoDB Commands Frequently Used

MongoDB commands that I frequently use while operation.

Find

Query using regex

db.collection.find({
		fieldName: {
			$regex: /regular_expression/
		}
	}
);

Join referential collection

db.collection.aggregate([
	{
		$lookup: {
			from: "list",
			localField: "list",
			foreignField: "_id",
			as: "list"
		}
	},
]);

Find entries with certain reference:

db.collection.aggregate([
	{
		$match: {
			list: ObjectId("objectid")
		}
	},
	{
		$lookup: {
			from: "list",
			localField: "list",
			foreignField: "_id",
			as: "list"
		}
	}
]);

Join only certain reference:

db.collection.aggregate([
  {
		$lookup: {
			from: "list",
			localField: "list",
			foreignField: "id",
			as: "list",
			pipeline: [
				{
					$match: {
						fieldName: { $ne: "to be excluded" }
					}
				}
			]
		}
	}
]);

List referential collection with count:

db.collection.aggregate([
	{
		$project: { list: 1 }
	},
	{
		$unwind: "$list"
	},
	{
		$group: {
			_id: "$list",
			count: { $count: {} }
		}
	},
	{
		$lookup: {
			from: "list",
			localField: "_id",
			foreignField: "_id",
			as: "listItem",
		},
	},
	{
		$replaceRoot: {
			newRoot: {
				$mergeObjects: [
					{ $arrayElemAt: ["$listItem", 0] },
					"$$ROOT"
				],
			},
		},
	},
	{
		$project: { listItem: 1 }
	},
]);

Insert

Copy one collection to other database

db.collection.find().forEach(function(d) {
	db.getSiblingDB("database2")["collection"].insertOne(d);
});

If you want to copy with new _id:

db.collection.find({}, { "_id": 0 }).forEach(function(d) {
	db.getSiblingDB("database2")["collection"].insertOne(d);
});

Update

Add an empty list field

db.collection.updateMany({}, [
	{
		$set: {
			list: []
		}
	}
]);

Replace string in the field

db.collection.updateMany({}, [
	{
		$set: {
			fieldName: {
				$replaceAll: {
					input: "$fieldName",
					find: "old string",
					replacement: "new string",
				},
			},
		},
	},
]);

Rename filed name

db.collection.updateMany({}, {
	$rename: { oldFieldName: "newFieldName" }
});

Copy one field value to another

db.collection.updateMany({}, [
	{
		$set: {
			newFieldName: "$oldFiledName"
		},
	},
]);

Copy one field value conditionally to another

db.collection.updateMany({}, [
	{
		$set: {
			newFieldName: {
				$cond: {
					if: {
						$eq: ["$oldFieldName", true]
					},
					then: 1,
					else: 0
				},
			},
		},
	},
]);

Remove a field

db.collection.updateMany({}, {
	$unset: {
		fieldName: ""
	}
});