1
votes

I'm learning mongodb and java and have the following question, is it possible to chain filters?

So my example document in mongo is as follows

{"_id" : "...."
    "name" :"Joe",
    "roles" : ["A","B", "C"],
    "value" : 1000
}

Can i do an update using a filter which will update depending on whether the document in mongo contain the roles

example my

listCriteria = ["B","D","E"]

so update this document if it has the roles B, D, E, update the value to 2000

In java I know I can use filters

Bson filter = Filters.eq("name", "Joe");
Filters.in("roles", roles);

.....
this.collection.updateOne(filter, updatedDocument...)

How can I chain it so that it updates the document with name "Joe" only if the roles in the documents contains atleast one in the list criteria

1
what do you mean by chain, is it chain of filters ?Digital Alchemist

1 Answers

1
votes

Must contain all 3 roles - use $all query operator:

db.people.update(
  {
    name: "Joe",
    roles: {$all: ["B", "D", "E"]}
  },
  {
    $set: {value: 2000}
  }
);

Must contain any of 3 roles - use $in query operator:

db.people.update(
  {
    name: "Joe",
    roles: {$in: ["B", "D", "E"]}
  },
  {
    $set: {value: 2000}
  }
);

About generally chaining filters, you can use $and query operator:

db.people.update(
  {
    $and: [
      {name: "Joe"},
      {roles: "B"},
      {roles: "D"},
      {roles: "E"}
    ]
  },
  {
    $set: {value: 2000}
  }
);