具有多个条件和切片的MongoDB查询 [英] MongoDB Query with multiple conditions and slice
问题描述
我有这个猫鼬查询:
return Domain.find({domain:req.params.domain})
.where('date').equals(date)
.exec(function (err, domain) {
if (!err) {
if (!isEmpty(domain[0].visitors)) {
domain[0]['visitors'] = domain[0].visitors.slice(0,99);
}
}
我想直接在数据库中切片,而不是在检索对象之后.猫鼬无法做到这一点,或者它没有记录在案,或者我没有找到文件.
I want to slice directly in the database and not after retrieving object. Mongoose cannot do this or it is not documented or I did not find documentation.
因此,我通过使用collection关键字来回退到node.js本机MongoDB驱动程序.
So I fall back to node.js native MongoDB Driver by using the collection keyword.
我的代码现在看起来如下所示,但失败了:
My code looks now as follow and fails:
return Domain.collection.find(
{ "domain":req.params.domain },
{ "date":date },
{ "visitors": { $slice:100 } },
function(err,domain){
if (!err) {
res.status(200).send({
domain:domain
});
}
完整代码: https://gist.github.com/nottinhill/b3837d4c913b9e5dd879
我尝试在MongoDB控制台中构造一个可以使用的查询,但是无法使这个简单的查询正常工作. MongoDB文档未显示如何在两个条件下进行查询.我要:
I tried in MongoDB console to construct a query that will work, but cannot get this simple query to work. MongoDB documentation does not show how to query with two conditions. I want to:
我想要的伪代码:
find
giveBack wholeDomainObject
where domain == domain
where date == date
also slice visitorsArray
推荐答案
投影是单个对象定义.另外,您可以查询"事物,而不是在符合条件的特定字段之外的投影中进行匹配. $slice
是特例默认情况下不排除投影中的其他字段:
Projection is a single object definition. Also you "query" for things rather than ask for matches in projections other than specific fields matching criteria. $slice
is a special case that does not exclude other fields in the projection by default:
Domain.collection.find(
{ "domain":req.params.domain, "date": date },
{ "visitors": { "$slice":100 } },
function(err,domain){
// process results here
}
);
可能还要注意,此处的$slice
(就像JavaScript一样)是定义的条目数",而不是数组索引中的n-1
引用.
Probably also to note that the $slice
here ( just like JavaScript ) is a defined "number of entries" and not a n-1
reference as in an array index.
这篇关于具有多个条件和切片的MongoDB查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!