I've got documents containing tags
array. I want to provide tags based recommendations on site, so I need to get documents containing same tags + documents that don't match 1 tag + documents that don't match 2 tags and etc...
How do I do that?
For comparison of different BSON type values, see the specified BSON comparison order. If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (for example, <value1> , <value2> , and so on).
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
MongoDB is a source-available cross-platform document-oriented database program for high-volume storage. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. Tags are custom labels you can apply to database clusters and other DigitalOcean resources.
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
example collection:
db.tags.insert({"tags":["red", "tall", "cheap"]});
db.tags.insert({"tags":["blue", "tall", "expensive"]});
db.tags.insert({"tags":["blue", "little", "cheap"]});
find all that include the tag "blue"
db.tags.find({tags: { $elemMatch: { $eq: "blue" } }})
find all tagged "blue" and only blue
db.tags.find({tags: "blue"})
find all tagged "blue" and "cheap"
db.tags.find({ tags: { $all: ["cheap", "blue"] } } )
find all not "blue"
db.tags.find({tags: { $ne: "blue" } })
find all "blue" and "cheap" but not "red" and not "tall"
not possible in my mongo db. From mongodb 1.9.1 on something like this should work, though (not tested):
db.tags.find({ $and: [ {tags: { $all: ["blue", "cheap"] } }, { tags: { $nin: ["red", "tall"] } } ] })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With