如何在MongoDB查询中的值中找不到

时间:2019-01-09 07:02:38

标签: mongodb mongodb-query

这里我有n份文件,下面是文件示例。

{
    "_id" : "ABC",
    "languagesknow" : {
        "lng" : [
            "1",
            "2"
        ]

    }
},
{
    "_id" : "CDF",
    "languagesknow" : {
        "lng" : [
            "3",
            "4"
        ]

    }
}

我的问题是假设我将输入作为一个数组传递。假设我在2 & 5 & 6中传递5 & 6意味着lng不在@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendAuthRequest(); } private void sendAuthRequest() { RequestQueue queue = Volley.newRequestQueue(this); JSONObject params = new JSONObject(); try { params.put("Username",userName); params.put("Password", passWord); JsonObjectRequest jsonObjReq = new JsonObjectRequest(com.android.volley.Request.Method.POST, url, params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); } }) { /** * Passing some request headers */ @Override public Map<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); return headers; } }; jsonObjReq.setRetryPolicy(new DefaultRetryPolicy( 60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); queue.add(jsonObjReq); }catch (JSONException je){ je.printStackTrace(); } } } 内,因此要打印值,如何做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要$setDifference运算符,请尝试:

db.collection.aggregate([
    {
        $match: {
            "languagesknow.lng": { $type: "array" }
        }
    },
    {
        $project: {
            languagesknow: {
                $setDifference: [ [ "2", "5", "6" ], "$languagesknow.lng" ]
            }
        }
    }
])

编辑:您可以将$match放在$setDifference前面,以过滤掉languagesknow.lng不是数组的所有文档(使用$type运算符)。

EDIT(2):如果要为整个集合获取单个数组,则需要将$group$unwind添加在一起,以将所有已知的语言收集到单个数组中,然后运行$setDifference在上面尝试:

db.collection.aggregate([
    {
        $match: {
            "languagesknow.lng": { $type: "array" }
        }
    },
    {
        $unwind: "$languagesknow.lng"
    },
    {
        $group: {
            _id: null,
            languagesknow: { $addToSet: "$languagesknow.lng" }
        }
    },
    {
        $project: {
            languagesknow: {
                $setDifference: [ [ "2", "5", "6" ], "$languagesknow" ]
            }
        }
    }
])