Reputation: 1502
I'm trying to search Mongo to see if any of the strings in my array are being used in my "images.src.large":
Strings to search for:
['/california/los-angeles/pool.jpg','/california/los-angeles/pizza.jpg']
Sample of what would be in my Mongo collection:
{
"_id": someNumber,
"name: "Name 1",
"images": [
{
"title": "Title 1",
"src": {
"small": "/california/los-angeles/pool-small.jpg",
"medium": "/california/los-angeles/pool-medium.jpg",
"large": "/california/los-angeles/pool.jpg"
}
},
{
"title": "Title 2",
"src": {
"small": "/california/los-angeles/oven-small.jpg",
"medium": "/california/los-angeles/oven-medium.jpg",
"large": "/california/los-angeles/oven.jpg"
}
}
],
},
{
"_id": someOtherNumber,
"name: "Name 2",
"images": [
{
"title": "Landscape",
"src": {
"small": "/alaska/badger/dog-small.jpg",
"medium": "/alaska/badger/dog-medium.jpg",
"large": "/alaska/badger/dog.jpg"
}
},
{
"title": "Food",
"src": {
"small": "/alaska/badger/pizza-small.jpg",
"medium": "/alaska/badger/pizza-medium.jpg",
"large": "/alaska/badger/pizza.jpg"
}
}
],
},
{
"_id": aDifferentNumber,
"name: "Bridge",
"images": [
{
"title": "Store",
"src": {
"small": "/hawaii/kilauea/pool-small.jpg",
"medium": "/hawaii/kilauea/pool-medium.jpg",
"large": "/hawaii/kilauea/pool.jpg"
}
},
{
"title": "Home",
"src": {
"small": "/hawaii/kilauea/tree-small.jpg",
"medium": "/hawaii/kilauea/tree-medium.jpg",
"large": "/hawaii/kilauea/tree.jpg"
}
}
],
},
Basically, what I'm trying to do is search my collection to see if the image is being used by searching the value of "images.src.large".
Upvotes: 0
Views: 76
Reputation: 3879
By using the $in
operator, described in this page in the documentation. You can query a field for any of several values. So the following query in your sample documents would have the result below.
> db.images.find({ "images.src.large" :
{ "$in" : ["/california/los-angeles/pool.jpg",
"/california/los-angeles/pizza.jpg"]
}
}).pretty();
{
"_id" : 1,
"name" : "Name 1",
"images" : [
{
"title" : "Title 1",
"src" : {
"small" : "/california/los-angeles/pool-small.jpg",
"medium" : "/california/los-angeles/pool-medium.jpg",
"large" : "/california/los-angeles/pool.jpg"
}
},
{
"title" : "Title 2",
"src" : {
"small" : "/california/los-angeles/oven-small.jpg",
"medium" : "/california/los-angeles/oven-medium.jpg",
"large" : "/california/los-angeles/oven.jpg"
}
}
]
}
Note that because both images are used in the same document, the query only returns one document. If you include a value that is present in another document, the query will return two documents. For example:
> db.images.count({ "images.src.large" :
{ "$in" : ["/california/los-angeles/pool.jpg",
"/alaska/badger/dog.jpg"]
}
});
2
Upvotes: 2