MongoDB:按标签获取文档 [英] MongoDB: get documents by tags

查看:73
本文介绍了MongoDB:按标签获取文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含tags数组的文档.我想在网站上提供基于标签的建议,因此我需要获取包含相同标签+不匹配1个标签的文档+不匹配2个标签的文档等.

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

我该怎么做?

推荐答案

示例集合:

db.tags.insert({"tags":["red", "tall", "cheap"]});
db.tags.insert({"tags":["blue", "tall", "expensive"]});
db.tags.insert({"tags":["blue", "little", "cheap"]}); 

找到所有包含标签"blue"的标签

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

找到所有不是蓝色"的

db.tags.find({tags: { $ne: "blue" } })

找到所有蓝色"和便宜",而不是红色"而不是高"

find all "blue" and "cheap" but not "red" and not "tall"

在我的mongo数据库中不可能.从mongodb 1.9.1开始,类似这样的东西应该可以工作(未经测试):

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

这篇关于MongoDB:按标签获取文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆