mongodb find by multiple array items
mongodb find by multiple array items
If I have a record like this;
{
“text”: “text goes here”,
“words”: [“text”, “goes”, “here”]
}
How can I match multiple words from it in MongoDB? When matching a single word I can do this;
db.find({ words: “text” })
But when I try this for multiple words, it doesn’t work;
db.find({ words: [“text”, “here”] })
I’m guessing that by using an array, it tries to match the entire array against the one in the record, rather than matching the individual contents.
db.inventory.insertMany([
{ item: “journal”, qty: 25, tags: [“blank”, “red”], dim_cm: [ 14, 21 ] },
{ item: “notebook”, qty: 50, tags: [“red”, “blank”], dim_cm: [ 14, 21 ] },
{ item: “paper”, qty: 100, tags: [“red”, “blank”, “plain”], dim_cm: [ 14, 21 ] },
{ item: “planner”, qty: 75, tags: [“blank”, “red”], dim_cm: [ 22.85, 30 ] },
{ item: “postcard”, qty: 45, tags: [“blue”], dim_cm: [ 10, 15.25 ] }
]);
db.bios.find(
{ _id: { $in: [ 5, ObjectId(“507c35dd8fada716c89d0013”) ] } }
)
This query selects all documents in the inventory
collection where the tags
field holds an array that contains at least one element that starts with either be
or st
.
db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )
db.inventory.update( { tags: { $in: ["appliances", "school"] } }, { $set: { sale:true } } )
db.find({ words: “text” })
db.find({ words: [“text”, “here”] })