【问题标题】:reduce mongo db query to pure array将 mongo db 查询减少为纯数组
【发布时间】:2018-04-05 14:50:38
【问题描述】:

当我运行db.abhishek.em.find({}) 我有

{ "_id" : ObjectId("5ac62d35b075e574b3e7eeaa"), "name" : "first", "employed" : true }
{ "_id" : ObjectId("5ac62d3fb075e574b3e7eeab"), "name" : "second", "employed" : true }
{ "_id" : ObjectId("5ac62d4eb075e574b3e7eeac"), "name" : "third", "employed" : false }

我想通过添加或链接一些东西来查找函数,将这个结果减少为一个简单的对象 id 数组,比如 db.a.b.find({employed:true}).somefunction() 可以返回以下数组 我想在更大的查询中使用嵌套在 $in 中的命令来实现某种关系查询

[
ObjectId("5ac62d35b075e574b3e7eeaa"),
ObjectId("5ac62d3fb075e574b3e7eeab")
]

------------------编辑----------------------

举个例子,我想通过跑步来雇佣员工

db.abhishek.another.find({id:{$in:db.abhishek.em.find({employed:true},{_id:1}).toArray()}})

或与此命令类似的东西不起作用

db.a.another 集合是

{ "_id" : ObjectId("5ac63de1b075e574b3e7eead"), "id" : ObjectId("5ac62d35b075e574b3e7eeaa"), "name" : "Lets say person 1" }
{ "_id" : ObjectId("5ac63df7b075e574b3e7eeae"), "id" : ObjectId("5ac62d3fb075e574b3e7eeab"), "name" : "Lets say person 2" }
{ "_id" : ObjectId("5ac63e06b075e574b3e7eeaf"), "id" : ObjectId("5ac62d4eb075e574b3e7eeac"), "name" : "Lets say person 3" }

------------------编辑---------------------- 解决了,看下面我的回答

【问题讨论】:

  • 你可能想使用toArray()
  • I want to use the command nested with $in in a bigger query to achieve some sort of relational querying -> 你真正想要什么?
  • toArray 为我提供了完整的对象数组(每个 bieng 都是完整的对象),我只想要一个对象 id 数组,而无需进一步嵌套以在 $in 中使用它
  • 试试db.abhishek.em.find({}, {_id:1})
  • @jonas-w 我基本上想使用类似 db.a.c.find({_id:{$in:db.a.b.find{employed:true}.somemethod_thatworkswith$in}}) 之类的东西

标签: javascript arrays mongodb mongodb-query aggregation-framework


【解决方案1】:

使用 MongoDB 仅提供模型中的那些字段。在 MongoDB 术语中,这称为投影。有一个 MongoDB 方法 .project(),您可以像这样链接到您的查询:

db.abhishek.em.find({}).project({});

应该这样做。如果要显式排除字段,请执行以下操作:

db.abhishek.em.find({}).project({name:0, employed:0});

然后,最后,以数组形式获取输出:

db.abhishek.em.find({}).project({name:0, employed:0}).toArray();

参考这里:

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/

【讨论】:

  • 找不到项目方法,怎么回事?
  • 实现因平台而异。我给出的例子是来自 NodeJS 的 MongoDB。你用的是什么平台?在我上面提供的参考资料中,单击页面顶部的 标签 对应于您的平台。
【解决方案2】:

感谢大家提供前进的方向和建议, 我能够使用以下方法成功地进行某种基于关系的查询

db.abhishek.another.find({id:{$in:db.abhishek.em.find({employed:true},{_id:1}).map(function(e) {return e._id})}},{name:1,_id:0})

它把这个作为输出

{ "name" : "Lets say person 1" }
{ "name" : "Lets say person 2" }

此查询从 em 集合中获取所有记录,并设置为 true,形成其数组,然后在查询“另一个”集合时将其传递给 $in 运算符以提供输出

toArray 方法用于转换嵌套在数组中的对象,因此 $in 运算符失败

感谢 @veeram 告知有关字段选择的信息

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多