1

[MONGO] I have a collection of places which is like this :

[
    { item: "journal",tags: ["blank", "red","blue","yellow"]},
    { item: "notebook",tags: ["red", "pink","green"]},
    { item: "paper", tags: ["red", "blank", "plain","black"]},
    { item: "planner",tags: ["blank", "blue","gray"]},
    { item: "postcard",tags: ["blue"] }
]

I want search for tags with 1 array search:["red", "blank","black"], how to get items, which the tags contains at least 1 element on aray search. and sorting .

expect result:

[
    { item: "paper",tags: ["red", "blank", "plain","black"]},
    { item: "journal",tags: ["blank", "red","blue","yellow"]},
    { item: "notebook",tags: ["red", "pink","green"]},
    { item: "planner", tags: ["blank", "blue","gray"]},
]
VietUngIT
  • 15
  • 6

1 Answers1

0

If you want to find all documents in a collection myitems, you can use the $or operator, an projection and the sort function.

Here's the query how to find for any element that either has the tag "red", "blank" or "black":

db.myitems.aggregate([
  {$project : 
    {tags: 1, item: 1, tag_count: {$size: "$tags" } }
  }, 
  {$match: 
    {$or: [{tags: "red"}, {tags: "blank"}, {tags: "black"}]} 
  }, 
  {$sort: {"tag_count": -1} } 
]);

This will return something like this:

{ "item" : "journal", "tags" : [ "blank", "red", "blue", "yellow" ], "tag_count" : 4 }
{ "item" : "paper", "tags" : [ "red", "blank", "plain", "black" ], "tag_count" : 4 }
{ "item" : "notebook", "tags" : [ "red", "pink", "green" ], "tag_count" : 3 }
{ "item" : "planner", "tags" : [ "blank", "blue", "gray" ], "tag_count" : 3 }

Explanation:

This uses the Aggregation pipeline in MongoDB, makes a projection of the given database in order to get the "tags" size, filters using the match projection and an $or operator over the tags and finally sorts the array over the "tags" size.

Hope this helps.

Alexander
  • 2,925
  • 3
  • 33
  • 36
  • but i want to sort items by the matching number of element – VietUngIT Apr 24 '18 at 09:34
  • [ { item: "paper",tags: ["red", "blank", "plain","black"]},// mactch 3 "red","blank","black" { item: "journal",tags: ["blank", "red","blue","yellow"]},//macth 2 "blank", "red" { item: "notebook",tags: ["red", "pink","green"]},// match 1 "red" { item: "planner", tags: ["blank", "blue","gray"]}, // match 1 "blank" ] sort decrease – VietUngIT Apr 24 '18 at 09:40
  • updated it once more: added projection (`$project`, `$match`, `$sort`). – Alexander Apr 24 '18 at 10:10