I have a collection as follows:
{
"_id" : ObjectId("5a6d9a1ee183f06dfd91dbf0"),
"date" : "20180126",
"oid" : "000",
"aid" : "0000000000",
"currentavalible" : "7",
"deletedbyuser" : "0",
"reply" : [
{
"oidaid" : "000000",
"nickname" : "****",
"date" : "2018-01-26 07:32:45",
"recomm" : "13",
"unrecomm" : "0",
"contents" : "aaaaaaaaaaaa"
},
{
"oidaid" : "000088",
"nickname" : "para****",
"date" : "2018-01-26 08:29:54",
"recomm" : "12",
"unrecomm" : "0",
"contents" : "bbbbbb"
}
]
}
To find in reply
that "recomm"
is "13"
i tried:
db.comments.find( { 'reply.recomm' : '13' })
db.comments.find( { 'reply' :{ 'recomm' : '13'} })
db.comments.find( {'_id' : ObjectId("5a6d9a1ee183f06dfd91dbf0"), 'reply.recomm' : '12' })
db.comments.find( {'_id' : ObjectId("5a6d9a1ee183f06dfd91dbf0"), 'reply' : { 'recomm' : '12'} })
And all fetched me nothing.
What seems to be the error in my syntax?
Best Answer
Both above query is looks fine and will be fetch the documents of records inside the comments collections.
I am sure that you are doing mistake something like not in the tree of particular database where your
comments
collection reside.Let's from beginning see here,
First i have create the StackExchange database.
Then i have created the comments collection inside the
StackExchange
database.And inside of comments collections i have insert the documents, which you have provided in souce code.
Now i want to fetch comments
documents
records from thecomments
collection, which is inStackExchange
database. First check throughmongo shell
, what is your current database like thatHere it mongo shell the current database is
StackExchange
.Then try to find the documents inside the collection through the
db.collection.find()
.From the first query db.comments.find( { 'reply.recomm' : '13' })
and from the query db.comments.find( {'_id' : ObjectId("5a6d9a1ee183f06dfd91dbf0"), 'reply.recomm' : '12' })
But from the mention below both query you shall not fetch the documents records from the comments collection due to their improper fetching of Array records.
As per MongoDB 3.6 Documented Here . If you want to fetch the array documents then you can use $ (projection), Or you can use Aggregation Pipeline Stages.
As you said only you want to
find
the records in reply that "recomm" is13
. so, you have to use$elemMatch (projection)
operator and your query will be as mention belowAfter the OP requirement to edit the code and execute the query to find out OP desire results.
Here i want to insert the second documents which having different
id
field records in comments documents.Now i only find out the
comments
collection documents , which having the "recomm":"13" records.