用Java中的$ in数组进行Mongo查询

时间:2016-02-12 17:33:42

标签: java mongodb mongodb-query

我正在尝试从JavaMongoDB创建此查询。 你知道如何在java中构建它吗?

db.node.find({
 connectedWithIds: { $in: [ 
     ObjectId('56bca32fe74a987ad8724da1')       
     ] }
})

我试着用这个:

ObjectId arr[] = {new ObjectId("5409ae2e2cdc31c5aa0ce0a5")};
BasicDBObject inQuery = new BasicDBObject("$in", arr);
BasicDBObject query = new BasicDBObject("connectedWithIds", inQuery);

但结果如下:

{ "connectedWithIds" : { "$in" : [ { "$oid" : "5409ae2e2cdc31c5aa0ce0a5"}]}}

并发生此错误:

error: {
    "$err" : "Can't canonicalize query: BadValue cannot nest $ under $in",
    "code" : 17287
}

1 个答案:

答案 0 :(得分:1)

I could overcome this error with the code below:

Function SearchCriteria()
Dim Brandtype, strGeneric, strManufacturer
Dim task, strCriteria As String

If IsNull(Me.cboBrand) Then
    Brandtype = "[BRAND] like '*'"
Else
    Brandtype = "[BRAND] = " & Me.cboBrand & "'"
End If

If IsNull(Me.cboGeneric) Then
    strGeneric = "[Generic] like '*'"
Else
    strGeneric = "[Generic] = " & Me.cboGeneric & "'"
End If

If IsNull(Me.cboManufacturer) Then
    strManufacturer = "[MANUFACTURER] like '*'"
Else
    strManufacturer = "[MANUFACTURER] = " & Me.cboManufacturer & "'"
End If

strCriteria = Brandtype & "And" & strGeneric & "And" & strManufacturer

    task = "Select GENERIC, BRAND,   MASTER_ID, PRODUCT_CATEGORY, MANUFACTURER, HTP_MODEL_QTR, HTP_SELECTION_REASON1, LU.ID, LU.Date_YYYYQX  from [tbl_Drug_Master] DM left outer join tbl_YYYYQX_LU LU on LU.ID = DM.HTP_MODEL_QTR Where " & strCriteria
    Me.tbl_Drug_Master_Date_subform.Form.RecordSource = task
    Me.tbl_Drug_Master_Date_subform.Form.Requery

End Function