![](/img/trans.png)
[英]How to get Mongoose to list all documents in the collection? To tell if the collection is empty?
[英]How to get counting of documents from another collection in mongoose?
我想知道如何获得特定的字段值?
在我的 mysql 中:
select *,
(select count(qty) from score where id = a.id) as d_qty
from mlbhitters as a order by no desc
在我的猫鼬中:
this.aggregate([
{
$match:options.query
},
{
$sort:{
no:-1
}
},
{
$limit:options.limit
}
]).exec(callback);
这是我应该在我的猫鼬中插入子查询的地方?
(select count(qty) from score where id = a.id) as d_qty
MongoDB 对我来说很难理解它是如何工作的 :(
考虑最简单的场景,您有两个集合,如下所示:
db.col1.save({ _id: 1 })
db.col2.save({ col1_id: 1 })
db.col2.save({ col1_id: 1 })
db.col2.save({ col1_id: 1 })
您可以使用$lookup通过指定哪些字段定义“关系”来将数据从col2
获取到col1
,然后您可以使用$size来获取元素的数量,请尝试:
db.col1.aggregate([
{
$lookup: {
from: "col2",
localField: "_id",
foreignField: "col1_id",
as: "col2docs"
}
},
{
$project: {
col2size: { $size: "$col2docs" }
}
}
])
输出:
{ "_id" : 1, "col2size" : 3 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.