简体   繁体   中英

Mongo DB query: find if a map stored in mongo contains a specific value

I have a mongo collection as follows:

    {
    "id": "510aec8e8426e96c156a0946",  
    "name": "ABC",
    "categoryToShardMap": null
    },
    {
    "id": "510aecd284268e0f60e547a5",
    "name": "XYZ",
    "categoryToShardMap": {
    "shoes": 1
    },
    {
    "id": "510aecbd84268e0f60e547a4",
    "name": "AAA",
    "categoryToShardMap": {
     "shoes": 3,
     "jeans": 2
     }

Where I have declared field 'categoryToShardMap' as :

    private HashMap<String, Long> categoryToShardMap;

I am trying to create a REST Api where if someone provides the shardId, he should get back the mongo document which contains it. For example: if I pass shardId = 3, I should receive the mongo document:

    {
    "id": "510aecbd84268e0f60e547a4",
    "name": "AAA",
    "categoryToShardMap": {
    "shoes": 3,
    "jeans": 2
    }

I am trying to use java to do this. But I am not sure how should I query this using mongotemplate or DBObject. Can someone point to me to some examples on how to query if a map stored in mongo document contains a specified value?

You can do this by $ne operator. Just check whether the field is not null.

Here is an example how you can achieve this using javadriver.

new BasicDBObject("categoryToShardMap", new BasicDBObject("$ne", null));

Or you can use $where operator to check the length of the array. This is explained in the following post:

Query for documents where array size is greater than 1

If you are looking for a specific value in a map you can use the following command:

DBObject query = BasicDBObjectBuilder.start().add("categoryToShardMap.shoes", 3).get(); // query for getting the documents whose "categoryToShardMap" field contains shoes with value 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM