Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

mongodb - Spring Mongo find if two field values are not equal

I have the following json

"_id" : ObjectId("5fd0b6d2db14e72272560029"),
"fooId" : "",
"fooNames" : [],
"fooDetails" : [ 
    {
        "foId" : "5fd0b63ddb14e7227255fffb",
        "fooSubId" : "5fd0b6d2db14e72272560029"
    }
],
...

I need to pull out the results of those documents whose _id is not equal to the nested object fooDetails.fooSubId.

How can I do this in spring Mongo?

--UPDATE-- For example below given are the entries in my collection

Entry one

 {
        "_id": ObjectId("5fd0b63ddb14e7227255fff1"),
        "fooId": "",
        "fooNames": [],
        "fooDetails": [
          {
            "foId": "5fd0b63ddb14e7227255fffb",
            "fooSubId": "5fd0b63ddb14e7227255fff1"
          },
        ]
      }

Entry two

{
    "_id": ObjectId("5fd0b63ddb14e7227255fff2"),
    "fooId": "",
    "fooNames": [],
    "fooDetails": [
      {
        "foId": "5fd0b63ddb14e7227255fffb",
        "fooSubId": "5fd0b63ddb14e7227255fff3",
        
      }
    ]
  }

Entry three

{
    "_id": ObjectId("5fd0b63ddb14e7227255fff2"),
    "fooId": "",
    "fooNames": [],
    "fooDetails": []
  }

The result should filter out the first one, it should give only the following two:

Result one

{
    "_id": ObjectId("5fd0b63ddb14e7227255fff2"),
    "fooId": "",
    "fooNames": [],
    "fooDetails": [
      {
        "foId": "5fd0b63ddb14e7227255fffb",
        "fooSubId": "5fd0b63ddb14e7227255fff3",
        
      }
    ]
  }

Result two

{
    "_id": ObjectId("5fd0b63ddb14e7227255fff4"),
    "fooId": "",
    "fooNames": [],
    "fooDetails": []
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understand correctly, you need a query similar like this:

Is only update the field fooDetails using $set and $filter.

With $set the field is replaced and with $filter you can look for objects into array which fooSubId is equal to the _id.

So, every object into array where fooSubId is not equal _id will not be in the array.

Edit, using $toObjectId to compare equal objects:

db.collection.aggregate([{
    "$set": {
      "fooDetails": {
        "$filter": {
          "input": "$fooDetails",
          "as": "id",
          "cond": { "$eq": [ {"$toObjectId": "$$id.fooSubId"}, "$_id" ] }
        }
      }
    }
}])

Example here

With this query, you can check this answer todo into Spring.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...