【问题标题】:how to find document with mongoDB using mongodb java in sub array of document?如何在文档的子数组中使用 mongodb java 查找带有 mongoDB 的文档?
【发布时间】:2015-04-14 10:39:15
【问题描述】:

这真的很难。我想找到select nodes.index where radio.mac_address="00:06:5A:03:2E:5B"。如何使用 java 在 MongoDB 中获取此查询? 我的mongodb如下。

我尝试了很多查询。其中之一如下

BasicDBObject query = new BasicDBObject("nodes.radios.mac_address", "mac_address value";
BasicDBObject fields = new BasicDBObject("nodes.$", 1);
DBCursor cursor = node_info.find(query, fields);

更新首先解决了

我怎样才能编写更新查询,如update rssiLocal="90" where mac_address="00:06:5A:03:2E:5B"

【问题讨论】:

  • 您能否检查此查询是否适用于您的收藏db.collectionName.find({"nodes":{"$elemMatch":{"radios":{"$elemMatch":{"mac_address":"00:06:5A:03:2E:5B"}}}}},{"nodes.$.index":1})
  • 不给我空文件。
  • 好的,所以这种情况下你应该使用 mongo 聚合docs.mongodb.org/ecosystem/tutorial/…
  • @yogesh 该查询工作正常。它给了我包含 mac_address 而不仅仅是索引的整个文档。
  • 如何更新radio_index where mac_address="some value"

标签: java mongodb mongodb-query mongodb-java


【解决方案1】:

在我的应用程序中,我使用以下方法。它根据给定的id找到一个对象,并通过Gson解析它并将其保存到相应的对象中。

 public MyEntity getValue(String id) {
        DB db = SessionManager.getInstance().db;
        DBCollection collection = db.getCollection("myCollection");
        BasicDBObject query = new BasicDBObject("_id", id);
        Object object = new Object();
        boolean found = false;

        DBCursor cursor = collection.find(query);
        try {
            while (cursor.hasNext()) {
                found = true;
                String str = (cursor.next().toString());
                Gson gson = new Gson();

                object = gson.fromJson(str, MyEntity.class);

            }
        } finally {
            cursor.close();
        }
        if (!found)
            return new MyEntity();
        MyEntity myEntity = null;
        myEntity = (MyEntity) object;
        return myEntity;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-02
    • 2014-09-26
    • 2019-09-24
    • 2021-07-25
    • 2016-08-25
    • 2016-04-18
    • 1970-01-01
    • 2015-12-19
    相关资源
    最近更新 更多