如何得到一个'和'与sails-mongodb工作的查询

我有一个在mongo shell中工作的查询

db.getCollection('insights').find({$and:[{author:/jim/i}]}) 

返回2条logging。

“或”代码调用waterline / sailsjs-mongo

 db('insights').find({ or: [ {or: [ {author: new RegExp( ".*"+"jim"+".*", 'i' )} ] } ] }).limit(req.params.limit).skip(req.params.offset).exec(function (err, insights) { ... } 

按预期返回2条logging。

如果我将“或”更改为“和”

 db('insights').find({ or: [ {and: [ {author: new RegExp( ".*"+"jim"+".*", 'i' )} ] } ] }).limit(req.params.limit).skip(req.params.offset).exec(function (err, insights) { ... } 

我得到0个不是预期的logging。 它应该返回2条logging。

我使用本地mongodb JavaScript客户端编写了一些代码。

 var MongoClient = require('mongodb').MongoClient, test = require('assert'); // Connection url var url = 'mongodb://localhost:27017/infosystem'; // Connect using MongoClient MongoClient.connect(url, function(err, db) { // Create a collection we want to drop later var col = db.collection('insights'); // Show that duplicate records got dropped col.find({$and:[{author: new RegExp('.*Jim.*','i')}]}).toArray(function(err, items) { test.equal(null, err); test.equal(2, items.length); db.close(); }); }); 

哪个运行时不会抛出断言。

  node test_insights.js 

mongodb是3.2.9版本,sails-mongodb和waterline是版本“0.12.1”

什么是在sails-mongodb中调用mongodb $和查询的正确方法?

https://docs.mongodb.com/manual/reference/operator/query/and/#and

$,并对两个或更多expression式(例如,expression式1,expression式2等)的数组执行逻辑与操作,并select满足数组中所有expression式的文档。 $和操作员使用短路评估。 如果第一个expression式(例如expression1)的计算结果为false,那么MongoDB将不会计算剩余的expression式。

所以在你的情况下,使用AND运算符是没有意义的,因为你也可以使用隐式AND

 db.getCollection('insights').find({author:/jim/i}) 

来到你的实际问题。 我不能使用本机mongodb重现此问题。 在shell中:

 db.collection.insert({name:'Foo', age:28}) db.collection.insert({name:'Bar', age:32}) db.collection.find() { "_id" : ObjectId("57ca84c374f2776cc983ad9e"), "name" : "Foo", "age" : 28 } { "_id" : ObjectId("57ca84cd74f2776cc983ad9f"), "name" : "Bar", "age" : 32 } db.collection.find({$and:[{name:new RegExp('.*Fo.*','i')}]}) { "_id" : ObjectId("57ca84c374f2776cc983ad9e"), "name" : "Foo", "age" : 28 } > db.collection.find({$or:[{$or:[{name:new RegExp('.*Fo.*','i')}]}]}) { "_id" : ObjectId("57ca84c374f2776cc983ad9e"), "name" : "Foo", "age" : 28 } > db.collection.find({$or:[{$and:[{name:new RegExp('.*Fo.*','i')}]}]}) { "_id" : ObjectId("57ca84c374f2776cc983ad9e"), "name" : "Foo", "age" : 28 } 

我得到了预期的结果。 但是,当我尝试使用嵌套的水线查询和/或我看到你描述的相同的问题。 让我们来看看下面的本地查询:

 db.collection.find({$or:[{$and:[{name:'Foo'}, {age:28}]}, {name:'Bar'}]}) 

正确返回:

 { "_id" : ObjectId("57ca84c374f2776cc983ad9e"), "name" : "Foo", "age" : 28 } { "_id" : ObjectId("57ca84cd74f2776cc983ad9f"), "name" : "Bar", "age" : 32 } 

现在让我们在waterline中创build相同的查询:

 Test.find({ or: [ {and: [{name:'Foo'},{age:28}]}, {name: 'Bar'} ] }) 

这返回[] 。 负责和/或查询的相关代码可以在这里find: https : //github.com/balderdashy/sails-mongo/blob/master/lib/query/index.js#L132

我敢肯定, 帆和mongo根本不支持嵌套和/或操作符,但我找不到任何证据。 您可以在他们的github页面上提交function请求。

作为一种解决方法,您可以使用本地的下层mongodb适配器来创build您的查询。 作为一个缺点,你的代码不会是数据库不可知的。