Skip to content

Instantly share code, notes, and snippets.

@rms1000watt
Last active April 12, 2024 18:36
Show Gist options
  • Save rms1000watt/0389d0ff12d17f437fb887b363422601 to your computer and use it in GitHub Desktop.
Save rms1000watt/0389d0ff12d17f437fb887b363422601 to your computer and use it in GitHub Desktop.
Hello World MongoDB Create Wildcard Index on Single Field

MongoDB Hello World Wildcard Index on Single Field

Reference: https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/create-wildcard-index-single-field/

Start MongoDB

# in one terminal
docker run -it --rm -p 27017:27017 mongo:7

# first install mongosh
# then in another terminal
mongosh

In Mongosh

db.createCollection("col");
db.col.insertOne({
  idx: {
    name: "ryan",
    height: 999,
    state : "CA"
  },
  person: true,
  car: "Toyota",
  food: "Pizza"
});

db.col.insertOne({
  idx: {
    brand: "anker",
    code: 383812,
    type: "charger"
  },
  price: 44,
  size: 11,
  location: "US"
});

db.col.insertOne({
  idx: {
    owner: "apple",
    device: "mba2022",
    price: 2000
  },
  quantity: 43334,
  weight: 122,
  location: "JPN"
});

db.col.createIndex({
  "idx.$**": 1
});

db.col.find({"idx.brand": "anker"});
db.col.find({"idx.brand": "anker", "idx.type": "charger"});

db.col.insertOne({
  idx: {
    brand: "anker",
    code: 33333,
    type: "stand"
  },
  price: 33,
  size: 44,
  location: "US"
});

db.col.insertOne({
  idx: {
    brand: "sonos",
    code: 444,
    type: "speaker1"
  },
  price: 444,
  size: 112,
  location: "US"
});

db.col.find({"idx.brand": {$in: ["anker", "sonos"]} });

db.col.insertOne({
  idx: {
    brand: "sonos",
    code: 4511,
    type: "stand"
  },
  price: 41,
  size: 12,
  location: "US"
});

db.col.find(
  {"idx.brand": {$in: ["anker", "sonos"]}, "idx.type": "stand"}
);

db.col.find(
  {"idx.brand": "anker", "idx.code": {$gt: 33333}}
);

db.col.insertOne({
  idx: {
    brand: "sonos",
    code: 999,
    type: "bracket",
    families: [233, 111, 555],
    mount: {
      type: "arm",
      vesa: true,
      bolt: {
        size: 34,
        metal: "zinc"
      }
    }
  },
  price: 2,
  size: 3,
  location: "US"
});

db.col.find(
  {"idx.families": {$in: [111]}}
);

db.col.find(
  {"idx.mount.bolt.metal": "zinc"}
);

All of these find() queries are index scans 👍 At this point you can play with MongoDB Compass and use the query explainer for more visual views

Keep in mind of the gotchas: https://www.mongodb.com/docs/manual/core/indexes/index-types/index-wildcard/reference/restrictions/#multi-field-query-predicates

Only 1 predicate can be used in the wildcard search, the rest will be filtered on

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment