首页 > 解决方案 > Array handling in mongodb

问题描述

I have the following two objects in my mongo db.

{

    "schema":
    {
        "tag1": [
        {
            "path": "/homeAddress",
                "sourceId": "1234"
        }],


            "something1": [
            {
                "path": "/Profile/properties/id",

            }],
            "iwantthis": [
            {
                "namespace": ["namespace1"]
            },
            {
                "namespace": ["namespace2"]
            }],

    }
}

{

    "schema":
    {
        "tag1": [
        {
            "path": "/homeAddress",
                "sourceId": "1234"
        }],


            "something1": [
            {
                "path": "/Profile/properties/id",

            }],
            "iwantthis": [
            {
                "namespace": ["namespace3"]
            },
            {
                "namespace": ["namespace4"]
            }],

    }
}

I am given two namespaces:

  1. namespace1

  2. namespace2

I have to form a query to fetch all the objects that have the two namespaces mentioned above.

MongoDB reference guide is not very helpful here. Any thoughts please?

标签: databasemongodbnosqlmongodb-query

解决方案


You can use $elemMatch operator to find inside the array with $in operator

db.collection.find({
  "schema.iwantthis": {
    "$elemMatch": {
      "namespace": { "$in": ["namespace1", "namespace2"] }
    }
  }
})

推荐阅读