[英]How to conditionally find items by Tag in mongodb
I am new to NoSQL
and MongoDB
and I am a little puzzled on what type of queries I can do and how to do them. 我是
NoSQL
和MongoDB
新手,我对可以执行哪种查询以及如何执行查询感到困惑。 my knowledge is limited to simpler queries 我的知识仅限于较简单的查询
I would like to make what I think its a complicated query within MongoDB
instead of using PHP
to sort it but I do not know if it is possible or how to do it. 我想在
MongoDB
中进行一个复杂的查询,而不是使用PHP
进行排序,但是我不知道这是否可行或如何进行。
I have a tag
field within my collection that is an array
. 我的集合中有一个
tag
字段,它是一个array
。 {tag: ["blue","red","yellow","green","violet"]}
. {tag: ["blue","red","yellow","green","violet"]}
。
First level problem: Let says I want to find all birds
that have the tag
blue & yellow & green
, where blue
is a must have tag
and any other colours are optional. 一级问题:让我说我想查找所有带有
tag
blue & yellow & green
birds
,其中blue
是必须具有tag
,其他任何颜色都是可选的。
Second level problem: Then I would like to order the query so that the birds
that have all the queried colours appear first. 第二层问题:然后,我想对查询进行排序,以便首先显示具有所有查询颜色的
birds
。
Is it possible to create this query in mongoDB? 是否可以在mongoDB中创建此查询? and if it is How could I do it?
如果是的话我该怎么办?
You can use aggregation framework . 您可以使用聚合框架 。 So for the next dataset:
因此,对于下一个数据集:
{ "_id":ObjectId(...), "bird":1, "tags":["blue","red","yellow","green","violet"]}
{ "_id":ObjectId(...), "bird":2, "tags":["red","yellow","green","violet"] }
{ "_id":ObjectId(...), "bird":3, "tags":["blue","yellow","violet"] }
{ "_id":ObjectId(...), "bird":4, "tags":["blue","yellow","red","violet"] }
{ "_id":ObjectId(...), "bird":5, "tags":["blue"] }
we can apply next query: 我们可以应用下一个查询:
colors = ["blue","red","yellow","green"];
db.birds.aggregate(
{ $match: {tags: 'blue'} },
{ $project: {_id:0, bird:1, tags:1} },
{ $unwind: '$tags' },
{ $match: {tags: {$in: colors}} },
{ $group: {_id:'$bird', score: {$sum:1}} },
{ $sort: {score:-1} },
{ $project: {bird:'$_id', score:1, _id:0} }
)
and will get result like this: 并会得到这样的结果:
{
"result" : [
{ "score" : 4, "bird" : 1 },
{ "score" : 3, "bird" : 4 },
{ "score" : 2, "bird" : 3 },
{ "score" : 1, "bird" : 5 }
],
"ok" : 1
}
Most of this you will have to do in your application. 您必须在应用程序中完成大部分操作。 In order to find all documents where a bird has the tag "blue", you can do this:
为了找到鸟标签为“ blue”的所有文档,可以执行以下操作:
db.collection.find( { tag: "blue" } );
Which colours are optional doesn't matter, as you have to find by the required tag anyway. 哪种颜色是可选的都无所谓,因为无论如何您都必须通过必需的标签来查找。
After finding them, you need to do a sort. 找到它们之后,您需要进行排序。 But sorting like you want (by their 3 colours) is not something you can do in MongoDB, and something you will have to do in PHP instead.
但是,在MongoDB中无法进行想要的排序(按其3种颜色),而必须在PHP中进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.