Skip to content

Instantly share code, notes, and snippets.

@steamonimo
Last active June 16, 2021 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steamonimo/f74942e63e47ec9f18152b49719e7c8a to your computer and use it in GitHub Desktop.
Save steamonimo/f74942e63e47ec9f18152b49719e7c8a to your computer and use it in GitHub Desktop.
MongoDB: queries

MongoDB: queries

Find with regular expression

db.getCollection('foo').find({"field": /.*test.*/})

Update or create field in all documents

db.getCollection('foo').updateMany({}, {$set: {field: value}})

Remove field in all documents

db.getCollection('foo').updateMany({}, {$unset: {field:1}});

Set field to value of another field in all documents

db.getCollection('foo').find({}).forEach(
    function (elem) {
        db.getCollection('foo').update(
            {
                _id: elem._id
            },
            {
                $set: {
                    field1: elem.field2
                }
            }
        );
    }
);

Update text field with javascript in all documents

db.getCollection("foo").find({}).forEach(function(elem,i) {
    elem.field1 = elem.field1.replace("FOO ","");
    db.getCollection("foo").save(elem);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment