投影文档查询包含某些字母的字段

时间:2016-02-25 18:31:27

标签: mongodb meteor

我正在尝试让MenuItems.find(..返回字段“group”包含在“menuGroup”中的字母的文档
例如:

如果menuGroup为“a”,则返回文件,其组等于a 如果menuGroup为“ab”,则返回组字段等于“a”的所有文档以及组字段等于“b”的文档。
阅读mongo docs,我无法理解。能否请你帮忙?感谢

var items =
  [
    {menuItem: "task1", group: "a"},
    {menuItem: "task2", group: "a"},
    {menuItem: "task3", group: "b"},
    {menuItem: "task4", group: "a"},
    {menuItem: "task5", group: "a"},
    {menuItem: "task6", group: "a"},
    {menuItem: "task7", group: "b"},
    {menuItem: "task8", group: "b"},
    {menuItem: "task9", group: "b"},
    {menuItem: "login", group: "a"},
    {menuItem: "logout", group: "a"}
  ]
if (!MenuItems.find().count()) {
    _.each(items, function (doc) {
        MenuItems.insert(doc);
    })
}

Meteor.publish('menuItems', function () {
    var menuGroup;
    if (!this.userId) { //no one is logged in
        menuGroup = 'a';
    } else {
        menuGroup = Meteor.users.findOne({_id: this.userId}).profile.menuGroup;
    }
    return MenuItems.find({group: menuGroup});  //what if menuGroup is "ab"
});

1 个答案:

答案 0 :(得分:2)

解决此问题的一种方法是split menuGroup,然后像这样使用mongo的$in运算符:

return MenuItems.find({group: {$in: menuGroup.split('')}});

因此,如果menuGroup'ab',则选择器最终会成为{group: {$in: ['a', 'b']}}