mongodb find by multiple array items

mongodb find by multiple array items

Asked on January 21, 2019 in MongoDB.
Add Comment


  • 13 Answer(s)

    The following document is Depends on whether you’re trying to find documents where words contains both elements (text and here) using $all:

    
    db.things.find({ words: { $all: ["text", "here"] }});
    

    or Else  either of them (text or here) using $in:

    
    db.things.find({ words: { $in: ["text", "here"] }});
    
    Answered on January 21, 2019.
    Add Comment

    db.coll.createIndex( { : } )

    Answered on January 23, 2019.
    Add Comment

    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.

    Answered on January 27, 2019.
    Add Comment

    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 ] }
    ]);

    Answered on January 28, 2019.
    Add Comment

    db.bios.find(
    { _id: { $in: [ 5, ObjectId(“507c35dd8fada716c89d0013”) ] } }

    )

    Answered on January 30, 2019.
    Add Comment

    Depends on whether you’re trying to find documents where words contains both elements (textand here) using $all:

    db.things.find({ words: { $all: ["text", "here"] }});

    or either of them (text or here) using $in:

    db.things.find({ words: { $in: ["text", "here"] }});

     

    Answered on January 30, 2019.
    Add Comment

    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/ ] } } )

    Answered on January 31, 2019.
    Add Comment

    db.coll.createIndex( { : } )

    Answered on February 2, 2019.
    Add Comment
    db.inventory.update(
                         { tags: { $in: ["appliances", "school"] } },
                         { $set: { sale:true } }
                       )
    Answered on February 2, 2019.
    Add Comment

    db.find({ words: “text” })
    db.find({ words: [“text”, “here”] })

    Answered on February 4, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.