Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: get documents by tags

Tags:

mongodb

tags

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?

like image 442
Daniel Avatar asked Aug 04 '11 11:08

Daniel


People also ask

What does $IN do in MongoDB?

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).

How do I get documents from MongoDB?

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.

What are tags in MongoDB?

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.

How do I query an array in MongoDB?

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>, ... } }


1 Answers

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"] } } ] })
like image 163
rompetroll Avatar answered Sep 19 '22 19:09

rompetroll