Запрос свойств Array mongodb - PullRequest
0 голосов
/ 03 июля 2018

Я пытаюсь получить здание по его идентификатору:

У меня есть коллекция под названием здания:

{
    "_id" : ObjectId("5b3b1cc79c23061e4d4634e4"),
    "buildings" : [ 
        {
            "id" : 0,
            "name" : "Farm",
            "description" : "Best farm of all times",
            "img" : "http://i.hizliresim.com/yq5g57.png",
            "wood" : "50",
            "stone" : "10"
        }, 
        {
            "id" : 1,
            "name" : "Storage",
            "description" : "Store your resources.",
            "img" : "http://i.hizliresim.com/yq5g47.png",
            "wood" : "100",
            "stone" : "200"
        }
    ]
}

Например, с идентификатором 0, я хотел бы получить данные фермы.

Я попробовал это: db.getCollection ( 'здания') найти ({ "buildings.id": 0}).

не работает

пример вывода:

{
                "id" : 0,
                "name" : "Farm",
                "description" : "Best farm of all times",
                "img" : "http://i.hizliresim.com/yq5g57.png",
                "wood" : "50",
                "stone" : "10"
            }

Пробовал:

var data = Buildings.find({},{buildings:{$elemMatch:{id:0}}}).fetch();
console.log(JSON.stringify(data));

результат: (все данные)

[{"_id":{"_str":"5b3b1cc79c23061e4d4634e4"},"buildings":[{"id":0,"name":"Farm","description":"Best farm of all times","img":"http://i.hizliresim.com/yq5g57.png","wood":"50","stone":"10"},{"id":1,"name":"Storage","description":"Store your resources.","img":"http://i.hizliresim.com/yq5g47.png","wood":"100","stone":"200"}]}]

Ответы [ 3 ]

0 голосов
/ 03 июля 2018

Попробуйте для этого

db.getCollection("collectionName").find({buildings: {"$elemMatch": {"id" : "0"}}})

Здесь метод find будет искать (курсор) данные со зданиями и id = 0

0 голосов
/ 03 июля 2018
db.collection.find({
    buildings: {
        $elemMatch: {
            id: 0
        }
    }
}, {
    'buildings.$': 1
})
0 голосов
/ 03 июля 2018

Вы можете использовать агрегацию $filter, чтобы исключить нежелательные элементы из массива

db.collection.aggregate([
  { "$match": { "buildings.id": 0 }},
  { "$project": {
    "shapes": {
      "$arrayElemAt": [
        { "$filter": {
          "input": "$buildings",
          "as": "building",
          "cond": {
            "$eq": [
              "$$building.id",
              0
            ]
          }
        }},
        0
      ]
    },
    "_id": 0
  }}
])
...