I have a mongo collection 'Student' with below documents
{
"_id" : ObjectId("5ccc2cded71acf061de1c2d8"),
"studentId" : "123",
"name" : "1",
"age" : NumberLong(0),
"section" : "A",
"state" : "State1",
"city" : "City1"
}
I have 100 documents with the above structure. Now i have a list with below structure
[{
"studentId": "123",
"state": "state1"
},
{
"studentId": "456",
"state": "state2"
}]
Is there any way in mongo that i can get the documents matching this list data in single db call. Iterating over list with criteria as studentId:123 and state:state1 will work but is how to get all list data without iterating in java?
All you need is a simple find query:
db.collection.find({$or: arr});
when arr is the sample array you showed.
You should note that mongo searches are case sensitive meaning with the sample array you gave no matches will be found since "state1" is not equal to "State1".
Related
I am sending an object to Firebase which has an ArrayList of users. I need to delete a user from this array. How can I do to know the position of the user in this array and delete it?
"room" : {
"-LswnaENRCSpJdB8-ZBg" : {
"description" : "",
"members" : [ {
"id" : "jh4Ch9rBgQPwBTfv...",
"name" : "John",
}, {
"id" : "5P6DzPIEuiSKU5UY...",
"name" : "Jack",
}, {
"id" : "nKTlIyaDc3O3gxNp...",
"name" : "Mary",
} ],
"name" : "MyRoom"
},
Thanks in advance!
How can I do to know the position of the user in this array and delete it?
There is currently no way you can create a query that can help you find a specific user that exists at a particular index in your members array.
To actually remove a particular user you'll need to load the entire members array, remove the user that you want client-side, and then write the entire array back.
I am storing data in a list element. That list attribute consists of multiple fields like year and name. Is there any way I can delete only the rows where year is 2018 like in relational databases??
Data is stored in this manner in which ID is primary key and some other fields as password, city etc. Below is how data is stored in quarters.
{
"q1risk" : "0",
"q1targets" : [ ]
}
UpdateItem succeeded:
{
"q2risk" : "100.0",
"q2targets" : [ {
"level" : "Basic",
"year" : "2017",
"name" : "1",
"completed" : "0",
"category" : "US"
}, {
"level" : "Basic",
"year" : "2017",
"name" : "2",
"completed" : "0",
"category" : "US"
}, {
"level" : "Basic",
"year" : "2018",
"name" : "3",
"completed" : "0",
"category" : "US"
} ]
}
Taken from this answer to a similar question, according to the DynamoDB UpdateExpression documentation, you can remove individual elements from the list using REMOVE ListAttribute[index].
However, there doesn't appear to be a way to conditionally delete list elements based on a condition.
Your best bet to minimize read/write throughput is to:
Query for the item with a CONTAINS filter condition and a projection expression on the list attribute.
If the item is found, it contains at least one element you want to remove, so find the indices of elements you want to remove.
Use REMOVE with the indices to remove those elements from the item's list attribute.
This is the documents format:
{
"_id" : ObjectId("123")
"types" : [ "PHONE", "ADDRESS" ]
},
{
"_id" : ObjectId("345")
"types" : [ "PHONE" ]
},
{
"_id" : ObjectId("567")
"types" : [ "PHONE", "NAME" ]
}
And this is the query to find elements which contains certain types:
public List<MyCollection> findByType(Type type) {
return getDatastore().createQuery(MyCollection.class)
.field("types").hasThisElement(type.toString())
.asList();
}
With this code, I get this error:
com.mongodb.MongoException: Can't canonicalize query: BadValue $elemMatch needs an Object
I tried using hasThisOne method, but always returns an empty array.
How can I do this query?
Why are you using a type.toString()?
I'd assume you have a List<Type> types in your entity, right? Then the query should use the enum as well and not its string representation.
And you can probably use:
getDatastore().createQuery(MyCollection.class)
.field("types").equal(type).asList();
Yes, even for arrays.
Can anyone explain me this mongodb query: -
#Query("{'$or':[{owner:?0, companyId:?1, status:?2},{companyId:?1, membersDetails:{'$elemMatch':{memberId:?0, status:?2}}}]}")
This is a Spring Data annotation that will be attached to a method signature something like this:
#Query("{'$or':[{owner:?0, companyId:?1, status:?2},{companyId:?1, membersDetails:{'$elemMatch':{memberId:?0, status:?2}}}]}")
List<MyClass> findByClassThings(String owner, String companyId, String status);
Or whatever the method is actually called as also with the appropriate types.
The query would act on data in storage something like this:
{
"owner": "A",
"companyId": "B",
"status": "C",
"membersDetails": [
{ "memberId": "B", "status": "X" },
{ "memberId": "C", "status": "C" },
]
},
{
"owner": "B",
"companyId": "B",
"status": "C",
"membersDetails": [
{ "memberId": "A", "status": "C" }
]
}
So when that method was called with something like this:
List<MyClass> results = MyClass.findByClassThings("A","B","C");
It would match both of those documents for the following reasons:
The first document matches because the elements in "owner", "companyId" and "status" match all of the supplied parameters as specified in the first query element to the $or expression:
{owner:"A", companyId:"B", status:"C"}`
The second document matches because the fields supplied are all present in the second query element of the $or condition. Being "companyId" is present at the top of the document and "status" is a match for an array element that also have the "memberId" with the same matching value to the first parameter:
{companyId:"B", membersDetails:{'$elemMatch':{memberId:"A", status:"C"}}}
In the later case $elemMatch requires that "both" the conditions "must" be present within the array elements being queried for a single element.
Try this
db.collection.find({$or: [{'owner': ?0, 'companyId': ?1, status:?2}, {'companyId': ?1, 'membersDetails': {'$elemMatch':{memberId:?0, status:?2}}}]});
Thanks
I have a collection students look like this:
{
"_id" : 10,
"name" : "Christiano Ronaldo",
"scores" : [
{
"type" : "exam",
"score" : 40.58945534169687
},
{
"type" : "quiz",
"score" : 4.30461571152303
},
{
"type" : "homework",
"score" : 62.36309025722009
},
{
"type" : "homework",
"score" : 32.1707802903173
}
]
}
How do I find out the lowest homework? Using javadriver.
You don't with normal querying. You always query for full documents rather than embedded elements within that document. If you make seperate documents for each score, e.g :
{
"_id" : 10,
"name" : "Christiano Ronaldo",
"type" : "exam",
"score" : 40.58945534169687
}
You can search highest/lowest exam score for Christiano Ronaldo. Note that the MongoDB Aggregation Framework can be used to answer your question but I'm going to assume that's out of scope here.
Also note that your schema is very problematic. There is no way to query a specific "homework" score with this schema. I would denormalize here and use a document per score.