【问题标题】:how to retrieve partial objects from object array in a field in mongodb如何从mongodb字段中的对象数组中检索部分对象
【发布时间】:2015-02-20 18:47:02
【问题描述】:

我有一个猫鼬模式,比如 -

db.foo.insert({one:'a',friends:[{two:'b',three:'c'},{two:'d',three:'e'},{two:'f',three:'G'}]})

现在我想要的是两个只检索 friends 数组的 'two' 部分 那就是我想在friends数组中的每个对象中找到一个包含two的所有值的数组 在输出中看起来像这样的mongodb中是否可以进行这样的投影-

['b','d','f']

【问题讨论】:

  • @JohnnyHK 我刚刚编辑了问题以包含预期的答案。
  • 不,它们是唯一值。我只是这样插入。抱歉忘记提早了

标签: mongodb mongoose mongodb-query


【解决方案1】:

aggregate 是你的答案

db.foo.aggregate({"$project" : {"two" : "$friends.two"}}).result

还有另一种方法可以做到这一点(获取不同的值)

db.foo.aggregate([      
    {'$project': {  
                    union:{$setUnion:["$friends.two"]}
                 }
    }
]).result;

【讨论】:

    【解决方案2】:

    您可以使用distinct

     db.foo.distinct('friends.two')
    

    输出:

    [
      "b",
      "d",
      "f"
    ]
    

    【讨论】:

    • 它说错误:未实现不同。在 try.mongodb.org 中。但在我的桌面上运行良好。感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多