Mongo查找内部和对象数组的多个匹配

我正在做的是有一个客户在页面上input的所有文件的列表。 然后我有多个search框,他们可以用来缩小文件。 每个search框都绑定到一个字段。 我希望能够在input时search和缩小结果。 我需要search的其中一个字段是一个包含其他对象的数组。 如果他们正在search的字段位于对象的基础中,但是我无法findsearch对象数组的方法,则可以成功完成此操作。 下面是一个完整对象的例子。

{ "_id" : "fNgY9TcdCnyEFwePT", "companyCode" : "demoAccount1", "tripNumber" : 5002, "tripNumberText" : "5002", "custID" : "TnfFBRt3bZvNrSRB7", "customerName" : "Am Transport Inc", "orderLoadNum" : "50021321", "orderPlacedDate" : ISODate("2016-01-27T08:00:00.000Z"), "orderDispatch" : [ { "Address" : "4111 Aurora Ave N", "Appt" : "", "Cases" : "", "City" : "Seattle", "Contact" : "", "Customer" : "ABC 1", "DatePuDel" : ISODate("2016-01-27T08:00:00.000Z"), "Email" : "", "Fax" : "", "Notes" : "", "ParsPaps" : "", "Phone1" : "", "Phone2" : "", "Ref" : "", "Skids" : "", "State" : "WA", "Suite" : "", "Weight" : "", "Zip" : "98103", "carrierCharges" : "", "carrierCurrency" : "CDN", "carrierName" : "", "driverName" : "", "stop" : true, "stopDelDate" : "", "stopDelTime" : "", "stopNum" : 0, "stopPuDate" : "", "stopPuTime" : "", "stopType" : "pickup", "trailerNum" : "", "truckNum" : "", "deliveryType" : "", "deliveryStatus" : "Entered" }, { "Address" : "8325 Main St", "Appt" : "", "Cases" : "", "City" : "Vancouver", "Contact" : "", "Customer" : "ABC 2", "DatePuDel" : ISODate("2016-01-27T08:00:00.000Z"), "Email" : "", "Fax" : null, "Notes" : "", "ParsPaps" : "", "Phone1" : "", "Phone2" : "", "Ref" : "", "Skids" : "", "State" : "WA", "Suite" : "", "Weight" : "", "Zip" : "V5X 3M3", "carrierCharges" : "", "carrierCurrency" : "CDN", "carrierName" : "", "driverName" : "Test Driver 1", "stop" : false, "stopDelDate" : "", "stopDelTime" : "", "stopNum" : 1, "stopPuDate" : "", "stopPuTime" : "", "stopType" : "delivery", "trailerNum" : 4412, "truckNum" : 101, "stopMiles" : "182.2", "deliveryType" : "Highway", "deliveryStatus" : "Dispatched", "truckNumText" : "101", "trailerNumText" : "4412" } ] } 

所以我testing了下面。 我只是想孤立一种方式来searchorderDispatch里面的多个字段,然后我会添加回其他字段。

  query = {"$and": [ { "$elemMatch" :{"orderDispatch.trailerNumText": {$regex: new RegExp('^' + $('input:text[name=traceBoardTrailerNumSetting]').val(), 'i')}}}, { "$elemMatch" :{"orderDispatch.carrierName": {$regex: new RegExp('^' + $('input:text[name=traceBoardCarrierSetting]').val(), 'i')}}}, { "$elemMatch" :{"orderDispatch.truckNumText": {$regex: new RegExp('^' + $('input:text[name=traceBoardTruckSetting]').val(), 'i')}}} ]}; 

我已经尝试了很多东西,似乎没有工作。 他正确的方向将不胜感激。

       

网上收集的解决方案 "Mongo查找内部和对象数组的多个匹配"

您的查询中有语法错误:

$elemMatch查询使用以下语法:

 db.collectionName.find( {"$and": [ { "orderDispatch" : { "$elemMatch" :{ "trailerNumText": {$regex: new RegExp('^' + 'insert your value here', 'i')}}} }, { "orderDispatch" : { "$elemMatch" :{ "carrierName": {$regex: new RegExp('^' + 'insert your value here', 'i')}}} }, { "orderDispatch" : { "$elemMatch" :{ "truckNumText": {$regex: new RegExp('^' + 'insert your value here', 'i')}}} } ]} )