【问题标题】:How to query for elements which contains given string in array of strings in MongoDB (with Mongoose)如何在MongoDB的字符串数组中查询包含给定字符串的元素(使用Mongoose)
【发布时间】:2016-03-19 09:09:05
【问题描述】:

这是我的用户架构

var UserSchema   = new Schema({
    name:String,
    groups: [String]
});

我想获取 x 中所有用户的姓名数组。

例如数据集:

[
    {
        "name":"a",
        "groups":[
            "1",
            "2"
        ]
    },
    {
        "name":"b",
        "groups":[
            "3x",
            "4"
        ]
    },
    {
        "name":"c",
        "groups":[
            "1",
            "4"
        ]
    },
    {
        "name":"d",
        "groups":[
            "2",
            "3"
        ]
    },
    {
        "name":"e",
        "groups":[
        ]
    }
]

我需要结果:

for group 1:
["a","c"]

for group 2:
["a","d"]

for group 3:
["b","d"]

for group 4:
["c"]

for group 5:
[]

可以这样写查询吗?怎么做?

【问题讨论】:

  • 您还应该添加您尝试过的内容(代码方面)

标签: arrays mongodb mongoose


【解决方案1】:

很简单,只需要两个阶段的聚合操作。

代码:

db.t.aggregate([
{$unwind:"$groups"},
{$group:{"_id":"$groups","names":{$addToSet:"$name"}}}
])

样本结果:

{ "_id" : "3x", "names" : [ "b" ] }
{ "_id" : "4", "names" : [ "c", "b" ] }
{ "_id" : "2", "names" : [ "d", "a" ] }
{ "_id" : "3", "names" : [ "d" ] }
{ "_id" : "1", "names" : [ "c", "a" ] }

【讨论】:

    猜你喜欢
    • 2017-11-07
    • 1970-01-01
    • 2013-10-03
    • 2011-12-23
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    相关资源
    最近更新 更多