匹配's _id在数组中作为子文档的一部分的文档
Mongo, match documents who's _id is in an array as part of a subdocument
使用MongoDB,我想在一个集合中找到所有文档,谁的_id出现在另一个集合中的子文档数组中。使用$in操作符在这里并不真正起作用,因为我只尝试匹配子文档中的单个值。
假设我有以下来自db.foo的文档:
{ _id: 1, foo: [ { bar_id: 1 }, { bar_id: 3 } ] }
和下面的db.bars集合:
{ _id: 1, foo: "bar" }
{ _id: 2, foo: "abr" }
{ _id: 3, foo: "rab" }
我想找到db中的所有文档。bar谁的_id可以在foo数组中找到(返回db。在本例中,包含_id 1和3的栏)。像这样:
var foos = db.foos.findOne( { _id: 1 } )
db.bars.find( _id: { $in: foos.foo.bar_id } )
当然,这行不通。我该怎么做呢?
您可以使用 collection.distinct
方法从foo
_id
值db.bars.find({ '_id': { '$in': db.foos.distinct('foo.bar_id', {'_id': 1}) }})
演示:> db.foos.distinct('foo.bar_id', {'_id': 1})
[ 1, 3 ]
> db.bars.find({ '_id': { '$in': db.foos.distinct('foo.bar_id', {'_id': 1})}})
{ "_id" : 1, "foo" : "bar" }
{ "_id" : 3, "foo" : "rab" }
相关文章:
- 返回一个关联数组,而不是mongoose中的文档数组
- 如何获取文档数组中元素的计数-MongoDB
- MongoDB findAndModify:>>>查找和更新文档数组中的对象
- 如何在猫鼬.js子文档数组中定义实例方法
- 通过node-js脚本将文档数组插入mongodb中的数据库时出现问题
- 通过 Meteor / Mongo 返回子文档数组
- Meteor:更新文档数组中的嵌套对象
- 通过Javascript中的JSON文档数组&使用KnockoutJS的JQuery
- 如何使用另一个文档数组中的id对光标进行排序
- 将字段插入子文档数组中.意外行为
- 如何从JSON文档数组中提取字段数组
- 如何在Mongodb中返回符合给定条件的子文档数组
- 按筛选的子文档数组元素计数排序
- 将新条目推入mongoDB文档数组
- Meteor AutoForm:如何用子文档数组更新模式值
- 我如何将文档数组更改为MongoDB shell中的值数组
- Mongodb:聚合子文档数组的值
- IBM worklight JSON存储删除文档数组
- 循环一个嵌入文档数组,将新值推入一个字段
- 插入到MongoDB文档数组的前面,没有$position和$each